2

The following code shows the difference between my local time (US central time) and UTC for every day over one year:

import datetime
startTs = 1293808443
intvl = 24 * 3600
for day in range(365):
    ts = startTs + day * intvl
    localTs = datetime.datetime.fromtimestamp(ts)
    utcTs = datetime.datetime.utcfromtimestamp(ts)
    print("%s\t%s" % (utcTs.strftime("%Y-%m-%d %H:%M:%S"), (utcTs - localTs)))

The result:

2010-12-31 15:14:03 6:00:00
2011-01-01 15:14:03 6:00:00
...
2011-03-11 15:14:03 6:00:00
2011-03-12 15:14:03 6:00:00
2011-03-13 15:14:03 5:00:00
2011-03-14 15:14:03 5:00:00
...
2011-11-04 15:14:03 5:00:00
2011-11-05 15:14:03 5:00:00
2011-11-06 15:14:03 6:00:00
2011-11-07 15:14:03 6:00:00
...
2011-12-29 15:14:03 6:00:00
2011-12-30 15:14:03 6:00:00

Without my specifying any time zone info, the datetime module seems to be aware not only of the time difference between my local time zone and UTC, but also of when daylight saving time starts and ends. This seems to contradict this answer to a similar question. Am I mistaken in my conclusion? If not, how do I get this time zone info from the OS/datetime module?

1 Answers1

0

Check out datetime docs.

In short, datetime and time objects have an optional timezone attribute, tzinfo that can be set to an instance of a subclass of the abstract tzinfo class.

These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect, only one concrete tzinfo class, the timezone class, is supplied by the datetime module.

The timezone class can represent simple timezones with fixed offset from UTC, such as UTC itself or North American EST and EDT timezones.

Ajay V
  • 51
  • 3
  • I never invoke the tzinfo or timezone classes in my example; the datetime objects I create are all naive. So how does datetime.datetime.utcfromtimestamp act as though it is time zone-aware by returning datetime objects that differ from the local ones correctly? – David Pitchford Aug 22 '17 at 15:01
  • Check out the datetime object description in the docs and go through the datetime.fromtimestamp() function [Check out the argument list] – Ajay V Aug 22 '17 at 15:10