Can't subtract datetime and timestamp in django?
我在db中有一个字段timestamp = models.DateTimeField(auto_now_add = True)。 我想找到时间戳和datetime.now()之间的区别。
当我尝试datetime.now() - 时间戳时,我收到错误:
1 | can't subtract offset-naive and offset-aware datetimes |
我该如何解决?
此错误指的是python存储时间的方式。 根据python文档:
There are two kinds of date and time objects:"naive" and"aware". This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment.
django文档还指出:
When time zone support is disabled, Django uses naive datetime objects
in local time. This is simple and sufficient for many use cases. In
this mode, to obtain the current time, you would write:
1 2 | import datetime now = datetime.datetime.now() |
When time zone support is enabled,
Django uses time-zone-aware datetime objects. If your code creates
datetime objects, they should be aware too. In this mode, the example
above becomes:
1 2 3 | import datetime from django.utils.timezone import utc now = datetime.datetime.utcnow().replace(tzinfo=utc) |
您应该确定是否需要在您的站点中识别时区,然后相应地调整存储时间。 要将感知的dt转换为天真,您可以使用pytz模块并执行以下操作:
1 | naive_dt = aware_dt.replace(tzinfo=None) |
这是有效的,因为所有python日期时间都有一个可选的时区属性
你好
简短的回答是:
1 2 3 | tz_info = your_timezone_aware_variable.tzinfo diff = datetime.datetime.now(tz_info) - your_timezone_aware_variable: |
您必须将时区信息添加到now()时间。
但是你必须添加变量的相同时区,这就是为什么我第一次读取tzinfo属性。