Nic*_*ite 5 python timezone datetime cross-platform python-dateutil
我很难过.我编写的日期清理功能在我的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
Run Code Online (Sandbox Code Playgroud)
为什么这在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'
Run Code Online (Sandbox Code Playgroud)
编辑:我尝试使用时区偏移量与小写%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'
Run Code Online (Sandbox Code Playgroud)
时区缩写不明确。例如,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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
796 次 |
最近记录: |