不能在django中减去datetime和timestamp? [英] Can't subtract datetime and timestamp in django?

查看:225
本文介绍了不能在django中减去datetime和timestamp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个字段timestamp = models.DateTimeField(auto_now_add = True)。我想找到那个时间戳和datetime.now()之间的区别。



当我尝试datetime.now() - 时间戳时,我得到错误:

 不能减去offset-naive和offset-aware datetimes 

如何解决这个问题?

解决方案

这个错误是指由python存储。根据python 文档



< blockquote>

有两种日期和时间对象:天真和知道。这个区别是指对象是否具有时区,夏令时或其他类型的算法或政治时间调整的概念。


django 文档还声明:


当禁用时区支持时,Django在本地时间使用了天真的datetime对象
。这对于许多用例来说是简单和足够的。在
这种模式下,要获取当前时间,您可以写:




  import datetime 
now = datetime.datetime.now()




启用时区支持时,
Django使用时区感知的datetime对象。如果您的代码创建
datetime对象,他们也应该知道。在这种模式下,上面的例子
成为:




  import datetime 
from django.utils.timezone import utc
now = datetime.datetime.utcnow()。replace(tzinfo = utc)

您应该确定是否要在您的网站中进行时区感知,然后相应地调整您的存储时间。要将感知dt转换为天真,可以使用 pytz模块,然后执行以下操作:

  naive_dt = aware_dt.replace(tzinfo = None)

这样做是因为所有python datetimes都有一个可选的时区属性, tzinfo ,可用于存储与UTC时间相关的dt偏移量的信息。


I have a field timestamp = models.DateTimeField(auto_now_add=True) in the db. I want to find the difference between that timestamp and datetime.now().

When I tried datetime.now() - timestamp, I get the error:

can't subtract offset-naive and offset-aware datetimes

How do I fix this?

解决方案

This error refers to how times are stored by python. According to the python documentation:

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.

The django documentation also states that:

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:

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:

import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)

You should determine whether or not you want timezone awareness in your site and then adjust your stored times accordingly. To convert an aware dt to naive you can use the pytz module and do this:

naive_dt = aware_dt.replace(tzinfo=None)

This works because all python datetimes have an optional timezone attribute, tzinfo, which can be used to store information on the dt's offset from UTC time.

这篇关于不能在django中减去datetime和timestamp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆