Search code examples
pythondatetimepytzstrptime

DST lost in datetime strptime with pytz Python


I have a string format

frmt = "%m-%d-%Y %I:%M:%S %p"

When I convert now() to this format & back, I lose DST.

print datetime.strptime(datetime.now().strftime(frmt), frmt).replace(tzinfo=pytz.timezone("US/Eastern")).dst()


print datetime.now(tz=pytz.timezone("US/Eastern")).dst()

The first print returns 1:00:00 the second print returns 0:00:00.
Is there a way to keep DST when using datetime.strptime?


Solution

  • Per the pytz documentation:

    This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document. ...

    You should also consider starting with "now" according to UTC, rather than according to your own computer's time zone. Then you can convert to the time zone you have in mind.

    Also, you should use "America/New_York" instead of "US/Eastern" as the latter is in the tzdb for backwards compatibility purposes only. It will work, but it's not preferred.

    utc_dt = pytz.utc.localize(datetime.utcnow())
    eastern_dt = utc_dt.astimezone(pytz.timezone("America/New_York"))