How to get time zone by passing city and country?

柔情痞子 提交于 2019-11-30 17:47:41

问题


In my django project I have a small hotel database which has fields city and country.

Can I get the timezone for that place by passing the city and country as parameters in someway.

The reason I want to do this is because I have some commands that work based on the difference in check-in time of hotels and the time at that hote now . Since datetime.now() gives naive datetime I cannot use it to compare with the hotel time.

How do I look forward to the solution. Thanks :)


回答1:


To resolve a time zone by city and country, you will first need to obtain latitude/longitude coordinates. There are multiple ways to do that, including various databases of cities, airport codes, or by reverse geocoding addresses.

Be aware that there are some cities in the world that have portions that observe different time zones. In those cases, you may have some small margin of error. See this post: can 2 timezone be for 1 city?

Since you said you are looking for locations of specific places (hotels), you would probably be better off geocoding the exact coordinates of each place using its full address. There are many services for this, such as the one provided by Google here.

Then use the coordinates in one of the services described here: How to get a time zone from a location using latitude and longitude coordinates?

Once you have the time zone id, such as Asia/Seoul or America/New_York, then you can use it in pytz functions, as user falsetru showed in his answer.

You could speed things up a bit by checking ahead of time if the city you are interested is already one of the ones defined in the time zone database. But there are thousands of more cities in the world than just those key cities with time zone ids.

Other Ideas

  • You could use GeoDjango with time zone map data found here.
  • You could look at Django-GeoNames and see if the time zones from GeoNames are included.
  • There might be some other Django or Python specific library out there exactly for this that I didn't find in my 5 minutes searching Google.


来源:https://stackoverflow.com/questions/17910948/how-to-get-time-zone-by-passing-city-and-country

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!