Get time zone information of the system in Python?

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

    For Python 3.6+ this can be easily achieved by following code:

    import datetime
    local_timezone = datetime.datetime.utcnow().astimezone().tzinfo
    
    print(local_timezone)
    

    But with Python < 3.6 calling astimezone() on naive datetime doesn't work. So we've to do it in a slightly different way.

    So for Python 3.x,

    import datetime
    local_timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
    
    print(local_timezone)
    

    Sample Output:
    On Netherlands Server(Python 3.6.9): CEST
    On Bangladesh Server(Python 3.8.2): +06

    More details can be found on this thread.

提交回复
热议问题