我想每天早上7点给用户发一封电子邮件。例如,用户1在美国/洛杉矶时区。客户2在美国/纽约时区,将在他们的时间7点收到一封电子邮件,但用户1的时间是凌晨4点。
我的客户对象如下所示:
class Customer(models.Model):
user = models.OneToOneField(User, related_name="customer")
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
reminder = models.TimeField(blank=True, null=True)
time_zone = TimeZoneField()
我可以用这个获取用户时区中的当前时间:
now = datetime.now()
settingstime_zone = timezone(settings.TIME_ZONE)
now = settingstime_zone.localize(datetime.now())
relative_time = now.astimezone(customer.time_zone)
这为我提供了用户相对于时区的正确时间。
我现在该如何检查该时区是否是早上7点?
检查日期时间对象的hour
属性就足够了
>>> from datetime import datetime
>>> from pytz import timezone
>>>
>>> customer_time_zone = 'America/Los_Angeles'
>>>
>>> #gets a non naive datetime (utc)
>>> utcnow = datetime.utcnow()
>>> utcnow = utcnow.replace(tzinfo=pytz.utc)
>>>
>>> #localize current utc with customer_time_zone
>>> relative_time = utcnow.astimezone(timezone(customer_time_zone))
>>> utcnow, relative_time
(datetime.datetime(2014, 9, 4, 5, 41, 2, 294757, tzinfo=<UTC>), datetime.datetime(2014, 9, 3, 22, 41, 2, 294757, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>))
>>> relative_time.hour
22
>>> utcnow.hour
5