Search code examples
pythonpython-3.xdatetimetimeunix-timestamp

Is Python3 safe from DST changes that may be coming?


Background

I've been unable to find a deeper explanation of the real source of the time value used by Python. Most of the documentation states that it 'gets the value from CPython' but does not go into detail about where it comes from beyond that point.

Some countries have recently changed or are looking to change their DST policies. This means that devices in those countries may auto-adjust the time zone and produce an incorrect GMT-based time until they are updated with the current policies.

That's not terrible on it's own, because operating systems usually have a great mechanism for updates. However, updating Python on those same systems is a very murky area sometimes. The OS may handle it, or perhaps Python is bundled with the application. Perhaps the OS is still getting critical updates but not Python updates.

The Problem / Question

We do not control how Python is being updated with our code. The concern is that we may get an incorrect unix-time-stamp from Python due to the GMT time calculation being out-of-date.

If Python delegates the GMT time calculation to the OS, then we can rest easy. If Python does not delegate it, then we may have to force the value to come from the OS (e.g. time+%s).

So the question is: Does Python3 get it's GMT time from the OS or from it's own calculation based on local time?


Solution

  • Python does not keep its own database of timezone information; it delegates to the OS and/or the pytz third-party package for all timezone-related calculations. UTC or local timestamps are fetched from the OS via the C gmtime_*() and localtime_*() functions from the platform's time.h.

    For the full story in source, have a look at the Python version of the datetime module, the C version of the same, the time module, and the pytime.c C module.