2014-09-04 58 views
1

我想每天在用戶上午7點發送一封電子郵件。例如,用戶1位於America/Los_Angeles時區。客戶2位於美國/紐約時區,他們將在7時收到電子郵件,但用戶1的時間是凌晨4點。在python不同時區比較相同的時間

我的客戶對象如下所示:

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點?

+1

您是否嘗試過使用'relative_time.hour'的hour財產? – w00dbunny 2014-09-04 03:54:58

回答

0

這是不夠的檢查DateTime對象

>>> 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 
相關問題