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 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 usingpytz. In that case, you can use the localize method to create timezone-aware datetimes that are adjusted for Daylight Savings Time. (Avoid usingdatetime.datetime‘stzinfoargument since it does not adjust for Daylight Savings Time.)