Python: Figure out local timezone

前端 未结 18 1620
野性不改
野性不改 2020-12-07 15:50

I want to compare UTC timestamps from a log file with local timestamps. When creating the local datetime object, I use something like:

>>&         


        
18条回答
  •  离开以前
    2020-12-07 16:16

    I have also been looking for a simple way to read the local host configuration and get timezone aware local_time based on it. As of python 3.6+ the simplest approach is use dateutil.tz which will read /etc/localtime and assist in getting timezone aware datetime object.

    Here is more info on it: https://dateutil.readthedocs.io/en/stable/tz.html

    The implementation to accomplish what you're looking for is as follows:

    from datetime import datetime
    from dateutil import tz
    local_time = datetime.now(tz.gettz())
    

    This will provide you the following local_time:

    2019-10-18 13:41:06.624536-05:00
    

    Additional Resources I used in researching this topic: Paul Ganssle Presentation about time zones: https://www.youtube.com/watch?v=l4UCKCo9FWY

    pytz: The Fastest Footgun in the West https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html

提交回复
热议问题