Get time zone information of the system in Python?

前端 未结 8 1090
情歌与酒
情歌与酒 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:41

    To obtain timezone information in the form of a datetime.tzinfo object, use dateutil.tz.tzlocal():

    from dateutil import tz
    myTimeZone = tz.tzlocal()
    

    This object can be used in the tz parameter of datetime.datetime.now():

    from datetime import datetime
    from dateutil import tz
    localisedDatetime = datetime.now(tz = tz.tzlocal())
    

    or the tz parameter of datetime object via datetime.datetime.astimezone():

    from datetime import datetime
    from dateutil import tz
    unlocalisedDatetime = datetime.now()
    localisedDatetime = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题