我试图比较当前日期和时间与使用比较运算符在模型中指定的日期和时间:

if challenge.datetime_start <= datetime.now() <= challenge.datetime_end:

脚本错误如下:

TypeError: can't compare offset-naive and offset-aware datetimes

模型是这样的:

class Fundraising_Challenge(models.Model):
    name = models.CharField(max_length=100)
    datetime_start = models.DateTimeField()
    datetime_end = models.DateTimeField()

我也有django使用区域日期和时间。

我还没有找到的是django使用DateTimeField()的格式。是天真还是有意识?我如何得到datetime.now()识别区域日期时间?


当前回答

Datetime.datetime.now不是时区感知的。

Django为此提供了一个帮助程序,它需要pytz

from django.utils import timezone
now = timezone.now()

您应该能够将现在与challenge.datetime_start进行比较

其他回答

Datetime.datetime.now不是时区感知的。

Django为此提供了一个帮助程序,它需要pytz

from django.utils import timezone
now = timezone.now()

您应该能够将现在与challenge.datetime_start进行比较

在我的例子中,我已经用pytz控制了时区,我已经用django.utils的时区将日期转换为本机:

import pytz
from django.utils import timezone

def _my_method(native_date, timezone):
    aware_date = datetime.now(pytz.timezone(timezone))
    return timezone.make_naive(aware_date) >  native_date

你也可以使用timezone.make_aware来感知本地日期

默认情况下,在Python中datetime对象是naive,因此需要将它们都设置为naive或感知型datetime对象。这可以使用:

import datetime
import pytz

utc=pytz.UTC

challenge.datetime_start = utc.localize(challenge.datetime_start) 
challenge.datetime_end = utc.localize(challenge.datetime_end) 
# now both the datetime objects are aware, and you can compare them

注意:如果已经设置了tzinfo,这将引发ValueError。如果你不确定,那就用

start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)

顺便说一下,您可以在datetime中格式化UNIX时间戳。带有时区信息的Datetime对象,如下所示

d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
    year=d.year,
    month=d.month,
    day=d.day,
    hour=d.hour,
    minute=d.minute,
    second=d.second,
    tzinfo=pytz.UTC)

它在我身上起作用。 在这里,我正在获取创建datetime的表,并在datetime上添加10分钟。 之后根据当前时间,将执行过期操作。

from datetime import datetime, time, timedelta
import pytz

在数据库datetime上增加了10分钟

Table_datetime = '2019-06-13 07:49:02.832969'(示例)

# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)

table_expire_datetime = table_datetime + timedelta(minutes=10 )

# Current datetime
current_datetime = datetime.now()


# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)


if expired_on < checked_on:
    print("Time Crossed)
else:
    print("Time not crossed ")

这对我很管用。

禁用时区。 使用challenge.datetime_start.replace (tzinfo = None);

您还可以对其他日期时间使用replace(tzinfo=None)。

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):