我有一個龐大的數據集的人與他們的位置數據。我的一個模塊只通過此數據集一次,並在我的數據庫中生成一個表以將位置數據映射到時區。此模塊使用地理編碼器,tzwhere和puts.timezone。之後,每當管理員想要向這些人發送電子郵件時,我的Django應用程序就會使用該時區映射表來識別每個人的當前時間,並在不適合向他們發送電子郵件的情況下向管理員報告。在一個城市和州或國家Python的當前時間
位置數據包括城市和州或國家名稱。
爲此,我結合以下四個文庫:
from datetime import datetime
from geopy import geocoders
from tzwhere import tzwhere
from pytz import timezone
爲了產生所述時區映射表,我的模塊做類似事情的以下示例代碼:
g = geocoders.GoogleV3()
tz = tzwhere.tzwhere()
locationList = ["Sackville, Canada", "Romania", "Mannheim, Germany", "New Delhi, India", "Trier, Germany", "Basel, Switzerland", "Bruxelles/Brussel, Belgium"]
for location in locationList:
place, (lat, lng) = g.geocode(location)
timeZoneStr = tz.tzNameAt(lat, lng)
timeZoneObj = timezone(timeZoneStr)
# Store timeZoneObj in the timezone mapping table.
然後,每次管理員想要發送電子郵件時,Django應用程序會遍歷每個人的時區,並識別他/她所在地區的當前時間。一個示例代碼如下:
# for each person:
# find the location and timezoneObj data for this person in the database.
now_time = datetime.now(timezoneObj)
print now_time
這裏是輸出:
Sackville, Canada : 2015-06-26 22:00:18.131000-03:00
Romania : 2015-06-27 04:00:18.240000+03:00
Mannheim, Germany : 2015-06-27 03:00:18.371000+02:00
New Delhi, India : 2015-06-27 06:30:18.531000+05:30
Trier, Germany : 2015-06-27 03:00:18.656000+02:00
Basel, Switzerland : 2015-06-27 03:00:18.812000+02:00
Bruxelles/Brussel, Belgium : 2015-06-27 03:00:18.921000+02:00
有沒有更有效的方法來做到這一點?
你知道什麼是'locationlist'是超前的時間線更多的東西? – IronManMark20
是的。我有一個包含所有位置數據的csv文件,但不幸的是,位置數據不是標準的。正如您在示例中看到的,其中一些是城市和州,其他則只是國家名稱。在國名的情況下,他們通常是小國。我手動檢查過,而且我非常確定這些國家,他們沒有多個時區。 – 1man
相關:[從Python/Django獲取城市的時區](http://stackoverflow.com/q/16505501/4279) – jfs