如何在不更改值的情况下使时间对象 TZ 感知?

How to make a time object TZ aware without changing the value?

我正在做一个 django 项目,我对时区感到困惑。

我有一个活动对象,它有 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

我如何比较这个时间以找出哪些对象现在处于活动状态?

您可以在原始日期时间对象上使用 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() 时间戳中删除时区信息:

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

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

How can i compare this times to find which objects are active right now?

随处使用时区感知日期时间对象。如果 USE_TZ = True then django uses timezone-aware datetime objects internally. In particular, timezone.now() returns 一个感知日期时间对象。

timezone.localtime(timezone.now()) returns the current time in the current time zone -- you don't need to call timezone.localtime() explicitly -- the current time zone is used for rendering automatically. You could use activate('Europe/Istanbul') to change the current time zone if the default time zone TIME_ZONE 不适合请求。

How to make a time object TZ aware without changing the value?

如果您已经配置USE_TZ=True;你不应该看到天真的日期时间对象。附上 current time zone to a naive datetime object, call 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)

这里是