python datetime.datetime not returning correct timezone info with daylight savings time
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/Pacifi开发者_运维问答c' PDT-1 day, 17:00:00 DST>)
I get the correct time.
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>)
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>)
Note that's 07/07/2011 08:00 AM UTC which is actually 01:00 AM PDT.
Anyone know why python would be giving me PST dates for the datetime.datetime constructor but not for adjust_datetime_to_timezone?
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>)
精彩评论