2015-09-28 34 views
2

我正在做一個django項目,我對時區感到困惑。如何在不更改值的情況下使時間對象TZ感知?

我有一個競選對象,它有publish_startpublish_end日期。

控制檯輸出示例;

campaingObject.publish_start 
datetime.datetime(2015, 9, 1, 0, 0) 

campaingObject.publish_end 
datetime.datetime(2015, 9, 28, 10, 10) 

我想獲得積極的對象,現在活躍。這意味着發佈開始時間少於當前時間,結束時間大於當前時間。

當我打電話:

datetime.now() 
datetime.datetime(2015, 9, 28, 5, 42, 37, 448415) 

這個結果是不是在我的時區。我可以讓我自己的時間的信息與

datetime.now(pytz.timezone('Europe/Istanbul')) 

,但這個時候,我不能比較值以找到哪些對象現在是活動的。

datetime.now(pytz.timezone('Europe/Istanbul')) > campaingObject.publish_end 
TypeError: can't compare offset-naive and offset-aware datetimes 

我該如何比較這個時間來查找哪些對象現在處於活動狀態?

回答

3

您可以使用django上的make_aware函數對您的樸素日期時間對象。您將不得不指定您的天真時間戳的時區。

now_ts = datetime.now(pytz.timezone('Europe/Istanbul')) 
now_ts > make_aware(campaingObject.publish_end, pytz.timezone('Europe/Istanbul')) 

https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.timezone.make_aware

在另一方面,你也可以使用make_naive功能,從您現在()日期和時間刪除時區信息:

now_ts = datetime.now(pytz.timezone('Europe/Istanbul')) 
now_naive = make_naive(now_ts, pytz.timezone('Europe/Istanbul')) 
now_naive > campaingObject.publish_end 

https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.timezone.make_naive

1
datetime.now(pytz.timezone('Europe/Istanbul')) > campaingObject.publish_end 
    TypeError: can't compare offset-naive and offset-aware datetimes 

如何比較此時間以查找哪些對象現在處於活動狀態?

無處不在使用時區感知的datetime對象。如果USE_TZ = True,則django在內部使用可識別時區的日期時間對象。特別是,timezone.now()返回一個知曉的日期時間對象。

timezone.localtime(timezone.now())返回當前時間current time zone - you don't need to call timezone.localtime() explicitly - 當前時區用於自動呈現。如果默認時區TIME_ZONE不適合請求,則可以使用activate('Europe/Istanbul')更改當前時區。

如何在不更改值的情況下使時間對象TZ感知?

如果您已配置USE_TZ=True;你不應該看到天真的日期時間對象。要將current time zone附加到天真的日期時間對象,請撥打dt = timezone.make_aware(naive_dt)

一般情況下,你可以調用pytz_timezone.localize()方法直接:

#!/usr/bin/env python 
from datetime import datetime 
import pytz 

tz = pytz.timezone('Europe/Istanbul') 
now = datetime.now(tz) # get the current time 
then = tz.localize(datetime.strptime('2015-09-15 17:05', '%Y-%m-%d %H:%M'), 
        is_dst=None) 

我這裏還有more details about what is is_dst flag and why do you need it, see "Can I just always set is_dst=True?" section

相關問題