Get timezone abbreviation from UTC offset

前端 未结 3 1899
独厮守ぢ
独厮守ぢ 2020-12-04 02:41

I have the UTC offset in my DB for the users:

+5:30 

How can I get the timezone abbreviation from this UTC offset using Python?

Suc

3条回答
  •  既然无缘
    2020-12-04 03:14

    You can get a set (zero or more) of timezone abbreviations (as specified in the tz database) that corresponds to the given UTC offset now:

    #!/usr/bin/env python
    from datetime import datetime, timedelta
    import pytz # $ pip install pytz
    
    utc_offset = timedelta(hours=5, minutes=30) # +5:30
    now = datetime.now(pytz.utc) # current time
    print({now.astimezone(tz).tzname() 
           for tz in map(pytz.timezone, pytz.all_timezones_set)
           if now.astimezone(tz).utcoffset() == utc_offset})
    

    Output

    set(['IST'])
    

    If you want to get abbreviations including the historical data:

    #!/usr/bin/env python
    from datetime import datetime, timedelta
    import pytz # $ pip install pytz
    
    utc_offset = timedelta(hours=5, minutes=30) # +5:30
    abbr = set()
    now = datetime.now(pytz.utc)
    for tz in map(pytz.timezone, pytz.all_timezones_set):
        dt = now.astimezone(tz)    
        tzinfos = getattr(tz, '_tzinfos',
                          [(dt.utcoffset(), dt.dst(), dt.tzname())])
        abbr.update(tzname for off, _, tzname in tzinfos if off == utc_offset)
    print(abbr)
    

    Output

    set(['IST'])
    

提交回复
热议问题