How to get a time zone from a location using latitude and longitude coordinates?

后端 未结 17 1559
走了就别回头了
走了就别回头了 2020-11-21 04:38

Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time z

17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 04:50

    It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):

    import pytz
    from datetime import datetime
    from tzwhere import tzwhere
    
    def timezoned_unixtime(latitude, longitude, dt):
        tzw = tzwhere.tzwhere()
        timezone_str = tzw.tzNameAt(latitude, longitude)
        timezone = pytz.timezone(timezone_str)
        timezone_aware_datetime = timezone.localize(dt, is_dst=None)
        unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
        return unix_time
    
    dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
    print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)
    

提交回复
热议问题