7

我有一个庞大的人员数据集及其位置数据。我的一个模块只遍历这个数据集一次,并在我的数据库中生成一个表来将位置数据映射到时区。该模块使用地理编码器、tzwhere 和 puts.timezone。之后,每当管理员想要向这些人发送电子邮件时,我的 Django 应用程序都会使用该时区映射表来识别每个人的当前时间,并在不是发送电子邮件的好时机向管理员报告。

位置数据包括城市和州或国家名称。

为此,我结合了以下四个库:

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

有没有更有效的方法来做到这一点?

4

1 回答 1

0

尝试更多类似的东西

import datetime
import pytz

utc = pytz.utc
utc_dt = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
eastern = pytz.timezone('US/Eastern')
loc_dt = utc_dt.astimezone(eastern)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt.strftime(fmt)
于 2015-06-27T01:40:44.750 回答