我很困惑。我在我的Mac上用Python2.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'发布于 2014-09-10 20:46:55
时区缩略语含糊不清。例如,EST可以是指美国的东部标准时间,也可以是澳大利亚的东部夏季时间。
因此,包含时区缩写的日期时间字符串不能可靠地解析为时区感知的datetime对象。
strptime的'%Z'格式将只匹配UTC、GMT或time.tzname中列出的时区缩写,后者与机器区域有关。
如果可以将日期时间字符串更改为包含UTC偏移量的字符串,则可以使用丁香醇将字符串解析为时区感知的datetime对象:
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-10 20:38:44
%Z将只接受GMT、UTC以及time.tzname中列出的任何内容,因为时区功能是特定于平台的,就像给定的这里一样。
对%Z指令的支持基于tzname中包含的值以及日光是否为真。正因为如此,它是特定于平台的,除了识别UTC和GMT之外,它们都是已知的(并且被认为是非日光节约时区)。
因此,通过运行以下命令,尝试找出平台支持哪些时区:
import time
time.tzname我得到以下信息:
('PST', 'PDT')因此,您最好的选择是将您的时间提前转换为默认允许的时区之一。
https://stackoverflow.com/questions/25774070
复制相似问题