5

我难住了。我编写的日期清理函数在我的 Mac 上的 Python 2.7.5 中工作,但在我的 Ubuntu 服务器上的 2.7.6 中却不行。

Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> date = datetime.strptime('2013-08-15 10:23:05 PDT', '%Y-%m-%d %H:%M:%S %Z')
>>> print(date)
2013-08-15 10:23:05

为什么这在 Ubuntu 上的 2.7.6 中不起作用?

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> date = datetime.strptime('2013-08-15 10:23:05 PDT', '%Y-%m-%d %H:%M:%S %Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '2013-08-15 10:23:05 PDT' does not match format '%Y-%m-%d %H:%M:%S %Z'

编辑:我尝试使用带有小写 %z 的时区偏移量,但仍然出现错误(尽管不同):

>>> date = datetime.strptime('2013-08-15 10:23:05 -0700', '%Y-%m-%d %H:%M:%S %z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
4

2 回答 2

4

时区缩写不明确。例如,EST 可以表示美国东部标准时间,也可以表示澳大利亚东部夏令时间。

因此,包含时区缩写的日期时间字符串不能可靠地解析为时区感知日期时间对象。

strptime'%Z'格式将仅匹配 UTC、GMT 或 中列出的时区缩写time.tzname,这取决于机器语言环境。

如果您可以将日期时间字符串更改为包含 UTC 偏移量的字符串,那么您可以使用dateutil将字符串解析为可识别时区的日期时间对象:

import dateutil
import dateutil.parser as DP
date = DP.parse('2013-08-15 10:23:05 -0700')
print(repr(date))
# datetime.datetime(2013, 8, 15, 10, 23, 5, tzinfo=tzoffset(None, -25200))
于 2014-09-10T20:46:55.070 回答
3

%Z将仅接受 GMT、UTC 和 中列出的任何内容time.tzname,因为时区功能是特定于平台的,如下所示

对 %Z 指令的支持基于 tzname 中包含的值以及日光是否为真。因此,它是特定于平台的,除了识别始终已知的 UTC 和 GMT(并且被认为是非夏令时时区)。

因此,请尝试通过运行以下命令来确定您的平台支持哪些时区:

import time
time.tzname

我得到以下信息:

('PST', 'PDT')

因此,您最好的选择可能是事先将您的时间转换为默认允许的时区之一。

于 2014-09-10T20:38:44.123 回答