我有一个模型 Player,它包含一个名为 time_joined 的 DateTimeField。我试图找到自 time_joined 以来耗时,所以我这样做:
curr_time = datetime.now()
print(player.time_joined)
print(curr_time)
print(curr_time - player.time_joined)
print('done')
这段代码的输出是:
2015-08-22 20:51:02.965000+00:00
2015-08-29 10:07:35.933000
然后它停止输出任何东西,出于某种我不明白的原因。
在此先感谢您的帮助!
请您参考如下方法:
发生这种情况是因为您正在减去天真和有意识的日期时间。
来自tzinfo部分:
An object of type time or datetime may be naive or aware. A datetime object
dis aware ifd.tzinfois notNoneandd.tzinfo.utcoffset(d)does not returnNone. Ifd.tzinfoisNone, or ifd.tzinfois notNonebutd.tzinfo.utcoffset(d)returnsNone,dis naive. A time objecttis aware ift.tzinfois notNoneandt.tzinfo.utcoffset(None)does not returnNone. Otherwise,tis naive.
您不能减去有意识的和天真的日期时间。您必须将两者都更改为 naive 或都更改为 aware datetime 才能执行减法。
让我们尝试在 shell 中减去 aware 和 naive 日期时间并查看结果。
In [10]: aware_datetime # an aware datetime having timezone info
Out[10]: datetime.datetime(2014, 8, 19, 23, 57, 56, tzinfo=<UTC>)
In [11]: current_naive_datetime = datetime.now()
In [12]: current_naive_datetime # naive datetime having no timezone info
Out[12]: datetime.datetime(2015, 8, 29, 20, 50, 2, 350872)
In [13]: print(current_naive_datetime - aware_datetime)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-59-2b7ea8141c3e> in <module>()
----> 1 print(current_naive_datetime - aware_datetime)
TypeError: can't subtract offset-naive and offset-aware datetimes
解决方案 1:将感知日期时间 aware_datetime 转换为原始日期时间
要执行减法,您可以将 aware_datetime 对象转换为 naive,方法是将其 tzinfo 替换为 None。
In [14]: my_naive_datetime = aware_datetime.replace(tzinfo=None)
In [15]: my_naive_datetime
Out[15]: datetime.datetime(2014, 8, 19, 23, 57, 56)
In [16]: print(current_naive_datetime - my_naive_datetime)
374 days, 20:52:06.350872
解决方案 2:将原始日期时间 datetime.now() 转换为感知日期时间
In [17]: import pytz
In [18]: aware_current_datetime = datetime.now().replace(tzinfo=pytz.UTC)
In [19]: aware_current_datetime
Out[19]: datetime.datetime(2015, 8, 29, 21, 21, 44, 227886, tzinfo=<UTC>)
In [20]: print(aware_current_datetime - aware_datetime)
374 days, 21:23:48.227886
(我不知道为什么你没有收到错误,因为我可以在我的机器上收到错误。)
