creating a timezone aware datetime object returns a wrong timezone

北慕城南 提交于 2020-06-28 04:02:36

问题


when I create a timezone aware datetime object for 'US/Eastern' and print it out, It shows as if my time zone is -4:56 instead of -4:00

>>> obj = datetime.datetime(2020, 7, 1, 9, 30, tzinfo=pytz.timezone('US/Eastern'))
>>> print(obj)
2020-07-01 09:30:00-04:56

instead of the expected:

2020-07-01 09:30:00-04:00

Am i doing something wrong?


回答1:


It is mentioned in the docs that constructing datetime objects doesn't work this way.

You are supposed to do this:

from datetime import datetime

from pytz import timezone

eastern = timezone('US/Eastern')
obj = eastern.localize(datetime(2020, 7, 1, 9, 30))
>>> obj
datetime.datetime(2020, 7, 1, 9, 30, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
>>> print(obj)
2020-07-01 09:30:00-04:00



回答2:


Have a look at dateutil - you can safely construct the tz-aware datetime object using your originally intended method:

import datetime
import dateutil

obj = datetime.datetime(2020, 7, 1, 9, 30, tzinfo=dateutil.tz.gettz('US/Eastern'))
print(obj)
# 2020-07-01 09:30:00-04:00

In Python 3.9, there will be zoneinfo as part of the standard lib for that task.



来源:https://stackoverflow.com/questions/62574766/creating-a-timezone-aware-datetime-object-returns-a-wrong-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!