【发布时间】:2013-03-19 13:03:48
【问题描述】:
我有一个日期:
from datetime import datetime
from datetime import tzinfo
test = '2013-03-27 23:05'
test2 = datetime.strptime(test,'%Y-%m-%d %H:%M')
>>> test2
datetime.datetime(2013, 3, 27, 23, 5)
>>> test2.replace(tzinfo=EST)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'EST' is not defined
>> test2.replace(tzinfo=UTC)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'UTC' is not defined
我在names 时区列表上找不到文档,我可以在replace.tzinfo= 调用中分配给tzinfo。
我已阅读以下内容,但没有任何内容:
http://docs.python.org/2/library/datetime.html#tzinfo-objects
我也在谷歌上搜索过。
编辑:我遵循了 unutbu 提供的解决方案,但得到以下信息:
>>> test = '2013-03-27 00:05'
>>> test
'2013-03-27 00:05'
>>> test2 = dt.datetime.strp(test, '%Y-%m-%d %H:%M')
>>> test2
datetime.datetime(2013, 3, 27, 0, 5)
>>> est = pytz.timezone('US/Eastern')
>>> utc = pytz.utc
>>> print(est.localize(test2))
2013-03-27 00:05:00-04:00
>>> print(utc.localize(test2))
2013-03-27 00:05:00+00:00
>>> print(est.localize(test2,is_dst=False))
2013-03-27 00:05:00-04:00
>>> print(est.localize(test2,is_dst=True))
2013-03-27 00:05:00-04:00
>>>
正如您所看到的,即使我提供了is_dst= 标志,偏移量仍然是“-04:00”,它是美国东部时间而不是美国东部时间。我很感激帮助。谢谢。
文档显示如下:
如果您坚持使用当地时间,这个库提供了一种明确构建它们的工具: http://pytz.sourceforge.net/#problems-with-localtime
>>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
>>> est_dt = eastern.localize(loc_dt, is_dst=True)
>>> edt_dt = eastern.localize(loc_dt, is_dst=False)
>>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))
2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500
eastern 在文档前面定义为eastern = timezone('US/Eastern')
这似乎表明is_dst= 标志应该进一步指定是否指定了夏令时。我会很感激为什么这对我的情况不起作用的帮助。
【问题讨论】:
-
我在尝试运行此程序时遇到错误:
AttributeError: 'module' object has no attribute 'strptime'。你确定你复制的代码正确吗? -
哎呀。您是否导入了 datetime 和 tzinfo?我将编辑我的原始帖子以包含它。
-
我的错,我导入了
datetime,而不是datetime.datetime。谢谢!