pythondatetimezoneinfo

Assigning a var to ZoneInfo("US/Eastern") at the start and re-using it in perpetuity without daylight saving issues?


I use the same timezone repeatedly in my python code when creating datetime objects. So far I've just been creating a new ZoneInfo object each time, similar to this:

dt = datetime.now(tz=ZoneInfo("US/Eastern"))

I thought the over-head would be worth it to ensure it accurately tracks daylight savings. But now I'm finding myself using it a lot, including iterating over hundreds of results often. And I'm wondering, if I just create a file with the timezones I usually use, something like:

# compononets/common/freq_tz.py
from zoneinfo import ZoneInfo
tz_us_east = ZoneInfo("US/Eastern")

and import it in my code:

from components.common.freq_tz import *

to reuse it all the time without recreating the object each time.

My only concern is that the program can run for weeks or months, and in that time, daylight savings may change the timezone's hour difference to UTC. If I still use that same object I created at the start, weeks or months ago... I'm unsure if it will cause issues when the daylight savings change happens.

I haven't been able to test this since it requires doing it just when the daylight savings change happens.


Solution

  • The timezone object doesn't change, regardless of when it's created. Otherwise even these two lines might be buggy, if the DST changes right in the microsecond between them:

    tz = ZoneInfo('US/Eastern')
    dt = datetime.now(tz=tz)
    

    No, it's the datetime object which reads the DST information from the timezone object as it needs it, relating to the time it needs:

    dt = datetime(2024, 1, 1, 10, 42, tzinfo=tz)
    dt = datetime(1983, 7, 7, 12, 8, tzinfo=tz)
    dt = datetime(2050, 12, 24, 9, 1, tzinfo=tz)
    

    It's perfectly safe to instantiate it only once.

    Whether it's a good idea to create a separate module with a whole load of timezone objects is a different question. That sounds overly complicated for some non-existent micro-optimisation. Instantiating timezones once near the code where you need it sounds like the better sweetspot.