Search code examples
pythontimezonepytz

How to get system timezone setting and pass it to pytz.timezone?


We can use time.tzname get a local timezone name, but that name is not compatible with pytz.timezone.

In fact, the name returned by time.tzname is ambiguous. This method returns ('CST', 'CST') in my system, but 'CST' can indicate four timezones:

  • Central Time Zone (North America) - observed in North America's Central Time Zone
  • China Standard Time
  • Chungyuan Standard Time - the term "Chungyuan Standard Time" is now rarely in use in Taiwan
  • Australian Central Standard Time (ACST)

Solution

  • A very simple method to solve this question:

    import time
    
    def localTzname():
        offsetHour = time.timezone / 3600
        return 'Etc/GMT%+d' % offsetHour
    

    Update: @MartijnPieters said 'This won't work with DST / summertime.' So how about this version?

    import time
    
    def localTzname():
        if time.daylight:
            offsetHour = time.altzone / 3600
        else:
            offsetHour = time.timezone / 3600
        return 'Etc/GMT%+d' % offsetHour