我很沮丧 我编写的日期清除功能在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'
时区缩写不明确。例如,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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句