我想每天早上7点向用户发送电子邮件。例如,用户1位于America / Los_Angeles时区。客户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点?
答案 0 :(得分:0)
足以检查datetime对象的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