我需要做什么
我有一个时区不知道的日期时间对象,我需要添加一个时区,以便能够将其与其他时区感知日期时间对象进行比较.我不想将我的整个应用程序转换为时区,而不是因为这个遗留案例.
我试过的
首先,要证明问题:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware …Run Code Online (Sandbox Code Playgroud) 我正在尝试解析像"Sat, 11/01/09 8:00PM EST"Python中的时间戳字符串,但我找不到能够处理缩写时区的解决方案.
我正在使用dateutil的parse()功能,但它不解析时区.是否有捷径可寻?
我有一个 UTC 时间戳和一个时区偏移时间戳(均以毫秒为单位):
utc_time = 1394452800000
timezoneoffset = -14400000
Run Code Online (Sandbox Code Playgroud)
如果我想得到datetime我会做的:
print datetime.utcfromtimestamp(utc_time/1000)
>>>2014-03-10 12:00:00
Run Code Online (Sandbox Code Playgroud)
我怎样才能本地化这个日期时间而且最终对象是时区感知的?
如果我除以timezoneoffset-14400000/(3600*1000) = -4(小时)。所以最终的输出应该是:
>>>2014-03-10 08:00:00-04:00
Run Code Online (Sandbox Code Playgroud)
我的尝试:
from pytz import timezone
from dateutil.tz import tzoffset
utc_time = 1394452800000
timezoneoffset = -14400000
tzinfooff = tzoffset(None, timezoneoffset/1000)
print timezone(tzinfooff).localize( datetime.utcfromtimestamp(utc_time/1000) )
>>>Traceback (most recent call last):
File "/Users/dionysis_lorentzos/Desktop/cmdline copy.py", line 25, in <module>
print timezone(tzinfo2).localize( datetime.utcfromtimestamp(time/1000) ).isoformat()
File "/usr/local/lib/python2.7/site-packages/pytz/__init__.py", line 162, in timezone
if zone.upper() == 'UTC':
AttributeError: 'tzoffset' object has no attribute 'upper'
Run Code Online (Sandbox Code Playgroud)