Python: Figure out local timezone

前端 未结 18 1698
野性不改
野性不改 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 16:12

    I want to compare UTC timestamps from a log file with local timestamps

    If this is your intent, then I wouldn't worry about specifying specific tzinfo parameters or any additional external libraries. Since Python 3.5, the built in datetime module is all you need to create a UTC and a local timestamp automatically.

    import datetime
    f = "%a %b %d %H:%M:%S %Z %Y"         # Full format with timezone
    
    # tzinfo=None
    cdatetime = datetime.datetime(2010, 4, 27, 12, 0, 0, 0)  # 1. Your example from log
    cdatetime = datetime.datetime.now()   # 2. Basic date creation (default: local time)
    print(cdatetime.strftime(f))          # no timezone printed
    # Tue Apr 27 12:00:00  2010
    
    utctimestamp = cdatetime.astimezone(tz=datetime.timezone.utc)  # 1. convert to UTC
    utctimestamp = datetime.datetime.now(tz=datetime.timezone.utc) # 2. create in UTC
    print(utctimestamp.strftime(f))
    # Tue Apr 27 17:00:00 UTC 2010
    
    localtimestamp = cdatetime.astimezone()               # 1. convert to local [default]
    localtimestamp = datetime.datetime.now().astimezone()  # 2. create with local timezone
    print(localtimestamp.strftime(f))
    # Tue Apr 27 12:00:00 CDT 2010
    

    The '%Z' parameter of datetime.strftime() prints the timezone acronym into the timestamp for humans to read.

提交回复
热议问题