datetime with pytz timezone. Different offset depending on how tzinfo is set [duplicate]

一世执手 提交于 2019-11-30 16:23:48

When you call ts2.replace(tzinfo=EST), the tzinfo object you're getting doesn't match the one you get with ts1:

>>> ts1
datetime.datetime(2014, 5, 16, 11, 51, 7, 916090, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
>>> ts2
datetime.datetime(2014, 5, 16, 11, 51, 30, 922692, tzinfo=<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>)

You end up with LMT instead of EDT.

The pytz documentation actually notes that using pytz with the tzinfo argument of standard datetime objects simply doesn't work for many timezones:

Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones.

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) '2002-10-27 12:00:00 LMT+0020'

It is safe for timezones without daylight saving transitions though, such as UTC:

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt) '2002-10-27 12:00:00 UTC+0000'

I'm not exactly sure why the first one works; perhaps because it doesn't actually have to convert anything when the object is initially constructed with the tzinfo object.

Edit:

Ah, the Python documentation notes that using datetime.datetime.now() with the tz arg is equivalent to:

EST.fromutc(datetime.utcnow().replace(tzinfo=EST))

Which means you're converting from UTC, which is safe with pytz. So that's why the first one works.

According to the documentation, the correct way to apply a time zone to a naive datetime is with the localize method.

ts1 = eastern.localize(datetime.datetime.now())

Also, I recommend you use avoid EST as a variable name, since it typically standard for "Eastern Standard Time", and America/New_York comprises both "Eastern Standard Time" (EST) and "Eastern Daylight Time" (EDT).

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