naive と aware を比較できません datetime.now() <= challenge.datetime_end 質問する

naive と aware を比較できません datetime.now() <= challenge.datetime_end 質問する

比較演算子を使用して、現在の日付と時刻をモデルで指定された日付と時刻と比較しようとしています。

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 を認識させるにはどうすればよいのでしょうか?

ベストアンサー1

デフォルトでは、datetimeオブジェクトはnaivePython で記述されているため、両方を naive オブジェクトまたは awaredatetimeオブジェクトにする必要があります。これは、次のようにして実行できます。

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

ValueError注: すでに設定されている場合は、 が発生しますtzinfo。不明な場合は、

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

ちなみに、次のようにタイムゾーン情報を使用して、datetime.datetimeオブジェクトのUNIXタイムスタンプをフォーマットすることができます。

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)

おすすめ記事