python datetime.datetime不返回带有夏令时的正确时区信息 [英] python datetime.datetime not returning correct timezone info with daylight savings time
问题描述
在用python创建日期时遇到问题,因为在某些情况下创建的日期不符合夏令时。
I'm having an issue creating dates in python, as the dates I create are not respecting daylight savings time in some scenarios.
例如,如果我去到我的外壳并运行
For example, if I go to my shell and run
>>> adjust_datetime_to_timezone(value=datetime.datetime.now(), from_tz=timezone('UTC'), to_tz=timezone('US/Pacific'))
datetime.datetime(2011, 7, 7, 12, 41, 16, 337918, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
我得到正确的时间。
我想创建一个日期作为当前日期的开始,所以我运行:
I want to create a date that is the start of the current date, so I run:
>>> datetime.datetime(year=2011, month=7, day=7, tzinfo=timezone('US/Pacific'))
datetime.datetime(2011, 7, 7, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
请注意, PST日期,因为当我将其转换为UTC时:
Note that is a PST date, because when I convert it to UTC:
>>> adjust_datetime_to_timezone(datetime.datetime(year=2011, month=7, day=7, tzinfo=timezone('US/Pacific')), from_tz=timezone('US/Pacific'), to_tz=timezone('UTC')) datetime.datetime(2011, 7, 7, 8, 0, tzinfo=<UTC>)
请注意,该时间是UTC时间07/07/2011 08:00,实际上是太平洋标准时间上午01:00。
Note that's 07/07/2011 08:00 AM UTC which is actually 01:00 AM PDT.
任何人都知道python为什么会给我datetime的PST日期。日期时间构造函数,但不适合Adjust_datetime_to_timezone?
Anyone know why python would be giving me PST dates for the datetime.datetime constructor but not for adjust_datetime_to_timezone?
推荐答案
因为我看到< DstTzInfo'US / Pacific'PST -1天,16:00:00 STD>
,看来您正在使用 pytz
。在这种情况下,您可以使用本地化方法来创建时区,夏令时调整的已知日期时间。 (请避免使用 datetime.datetime
的 tzinfo
参数,因为它不会针对夏令时进行调整。)
Since I see <DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>
, it appears you are using pytz
. In that case, you can use the localize method to create timezone-aware datetimes that are adjusted for Daylight Savings Time. (Avoid using datetime.datetime
's tzinfo
argument since it does not adjust for Daylight Savings Time.)
import pytz
import datetime as dt
now=dt.datetime(year=2011, month=7, day=7)
utc=pytz.utc
pacific=pytz.timezone('US/Pacific')
now_pacific=pacific.localize(now)
now_utc=now_pacific.astimezone(utc)
print(repr(now_pacific))
# datetime.datetime(2011, 7, 7, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
print(repr(now_utc))
# datetime.datetime(2011, 7, 7, 7, 0, tzinfo=<UTC>)
这篇关于python datetime.datetime不返回带有夏令时的正确时区信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!