Display correct Local Time with DST Change

Ok, so here is why this is hard information to find. It isn’t standard practice, so you wont find it suggested by almost any documentation. Why this is, is that this information is not really “ground truth” in programming, it is the local computers set computer time, which can be changed by any user at any time.
Programmers don’t like this, because it means the user can make themselves any time they like (1000’s of years in the future for example) which could create use cases that most people just don’t want to deal with.

That being said:

import time

    if time.localtime().tm_isdst:
      print("DST")
    else:
      print("NOT DST")
    

.tm_isdst just resovles to a 1 or a zero (…so falsey).

time.localtime().tm_zone will give you a zero padded string for your UTC timezone ( so “-05” for UTC -5:00 where I am.

time.strftime("%z", time.localtime())

…is going to give you an offset string with the adjusted for local client browsers computer time with daylight savings time. (so -0400 for me as of October 29th 2021, since daylight savings time is active where I am)
The nice thing about this is, if you tell a modern OS that you live in a place that does not have Daylight Savings time, time.localtime() should adjust for this.

As an example, Arizona in the United States does not observe but states it borders does, making it possible for your time to change by 1hr by traveling to Nevada, but only for about 1/2 the year :crazy_face:

You can use this offset string to “re-create” a timezone aware datetime object by plugging the string back into an unaware datetime object.

This was a pain to research, My use case was that I had to interpret some live data that had timestamps from an old system that does not have offsets recorded, so my local system adds the local timezone (same location as the old system) before writing to an anvil data-table datetime column so I can compare datetimes using anvil. This is only accurate because it is live information, (actual people workers doing things) and the information is never generated at night during the dst shift.

2 Likes