将无意识时间戳转换为UTC转换的感知时间戳

时间:2013-08-11 20:05:15

标签: python timezone pytz

我使用下面的代码创建了一个不知道的日期时间,因为时间是在“US / Eastern”,所以我需要在UTC中使用它。我想先让日期时间知道EST,然后转换为UTC。

import datetime
import pytz
from pytz import timezone
dt = "8/8/2013 4:05:03 PM"
dt = datetime.datetime.strptime(dt,"%m/%d/%Y %I:%M:%S %p")
unaware_est = dt.strftime("%Y-%m-%dT%H:%M:%S")
localtz = timezone('US/Eastern')
utc = localtz.localize(unaware_est)

错误讯息:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/druidry-codebase/services/xignite/test.py", line 120, in <module>
    quote_time = localtz.localize(quote_time)
  File "/usr/local/lib/python2.7/dist-packages/pytz-2013b-py2.7.egg/pytz/tzinfo.py", line 303, in localize
    if dt.tzinfo is not None:
AttributeError: 'str' object has no attribute 'tzinfo'

2 个答案:

答案 0 :(得分:6)

localize方法需要datetime,而不是字符串。因此,应删除对strftime的调用。

import datetime
import pytz
from pytz import timezone
dt = "8/8/2013 4:05:03 PM"
unaware_est = datetime.datetime.strptime(dt,"%m/%d/%Y %I:%M:%S %p")
localtz = timezone('US/Eastern')
aware_est = localtz.localize(unaware_est)

这仍然不能给你UTC。如果你想要,你需要跟进:

utc = aware_est.astimezone(pytz.utc)

答案 1 :(得分:4)

Python字符串和日期时间对象不可互换。您需要明确地转换它们:

from datetime import datetime
import pytz # $ pip install pytz

# convert the time string to a datetime object
dt_str = "8/8/2013 4:05:03 PM"
unaware_est = datetime.strptime(dt_str,"%m/%d/%Y %I:%M:%S %p")

# make it a timezone-aware datetime object 
aware_est = pytz.timezone('US/Eastern').localize(unaware_est, is_dst=None)

# convert it to utc timezone
utc_dt = aware_est.astimezone(pytz.utc) # `.normalize()` is not necessary for UTC

# convert it to a string
print(utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")) # -> 2013-08-08T20:05:03Z

注意:is_dst=None断言输入本地时间存在且不明显。请参阅problems with local time