我需要做什么
我有一个不了解时区的日期时间对象,我需要向其中添加一个时区,以便能够将其与其他时区感知的日期时间对象进行比较。我不想在不知道这一遗留情况的情况下将整个应用程序转换为时区。
我尝试过的
首先,演示一下问题:
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 datetimes
首先,我尝试了 astimezone:
>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>
失败并不奇怪,因为它实际上是在尝试进行转换。更换似乎是一个更好的选择(根据如何在 Python 中获取“时区感知”的 datetime.today() 值? https://stackoverflow.com/questions/4530069/python-how-to-get-a-value-of-datetime-today-that-is-timezone-aware):
>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>
但正如您所看到的,replace 似乎设置了 tzinfo,但没有让对象感知。我正准备在解析输入字符串之前对它进行修改以使其具有时区(我正在使用 dateutil 进行解析,如果这很重要的话),但这看起来非常混乱。
另外,我在 Python 2.6 和 Python 2.7 中都尝试过这一点,得到了相同的结果。
Context
我正在为一些数据文件编写解析器。我需要支持一种旧格式,其中日期字符串没有时区指示器。我已经修复了数据源,但我仍然需要支持旧数据格式。由于各种商业BS原因,遗留数据的一次性转换不是一种选择。虽然总的来说,我不喜欢硬编码默认时区的想法,在这种情况下,它似乎是最好的选择。我有合理的信心知道所有有问题的遗留数据都是采用 UTC 格式的,因此我准备接受在这种情况下默认的风险。