Get time zone information of the system in Python?

前端 未结 8 1125
情歌与酒
情歌与酒 2020-12-02 11:40

I want to get the default timezone (PST) of my system from Python. What\'s the best way to do that? I\'d like to avoid forking another process.

8条回答
  •  悲哀的现实
    2020-12-02 12:42

    Gives a UTC offset like in ThomasH's answer, but takes daylight savings into account.

    >>> import time
    >>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
    >>> offset / 60 / 60 * -1
    -9
    

    The value of time.timezone or time.altzone is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.

    time.localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).

    EDIT: marr75 is correct, I've edited the answer accordingly.

提交回复
热议问题