pytz: return Olson Timezone name from only a GMT Offset

前端 未结 1 1329
时光说笑
时光说笑 2020-12-19 21:48

I have a legacy application i\'m going to need to supplement some data with. Currently, we have a DB table storing US (and its territories) zip codes, along with a GMT Offse

相关标签:
1条回答
  • 2020-12-19 21:58

    UTC offset by itself may be ambiguous (it may correspond to several timezones that may have different rules in some time period):

    #!/usr/bin/env python
    from datetime import datetime, timedelta
    import pytz # $ pip install pytz
    
    input_utc_offset = timedelta(hours=-4)
    timezone_ids = set()
    now = datetime.now(pytz.utc) #XXX: use date that corresponds to input_utc_offset instead!
    for tz in map(pytz.timezone, pytz.all_timezones_set):
        dt = now.astimezone(tz)    
        tzinfos = getattr(tz, '_tzinfos',
                          [(dt.tzname(), dt.dst(), dt.utcoffset())])        
        if any(utc_offset == input_utc_offset for utc_offset, _, _ in tzinfos):
            # match timezones that have/had/will have the same utc offset 
            timezone_ids.add(tz.zone)
    print(timezone_ids)
    

    Output

    {'America/Anguilla',
     'America/Antigua',
     'America/Argentina/Buenos_Aires',
     ...,
     'Cuba',
     'EST5EDT',
     'Jamaica',
     'US/East-Indiana',
     'US/Eastern',
     'US/Michigan'}
    

    You can't even limit the list using pytz.country_timezones['us'] because it would exclude one of your examples: 'America/Puerto_Rico'.


    If you know coordinates (latitude, longitude); you could get the timezone id from the shape file: you could use a local database or a web-service:

    #!/usr/bin/env python
    from geopy import geocoders # pip install "geopy[timezone]"
    
    g = geocoders.GoogleV3()
    for coords in [(18.4372,  -67.159), (41.9782,  -71.7679), (61.1895,  -149.874)]:
        print(g.timezone(coords).zone)
    

    Output

    America/Puerto_Rico
    America/New_York
    America/Anchorage
    

    Note: some local times may be ambiguous e.g., when the time falls back during end of DST transition. You could pass is_dst=None to .localize() method to raise an exception in such cases.

    Different versions of the tz database may have different utc offset for some timezones at some dates i.e., it is not enough to store UTC time and the timezone id (what version to use depends on your application).

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