datetime类型offset-aware与offset-navie

有时,我们使用python 的datetime模块比较两个时间的前后关系时,会出现报错:

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

这是因为两个时间不属于同一类型,offset-naive是不含时区的类型,而offset-aware是有时区类型,两者自然不能比较。

我们可以通过判断datetime对象的tzinfo属性,来获悉他是何种类型

In [17]: import datetime
In [18]: import pytz

In [19]: now=datetime.datetime.now()

In [20]: now
Out[20]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)

In [21]: now.tzinfo==None
Out[21]: True

上述代码中now就是一个offset-naive型,就是一个不含时区的datetime。下面代码可以把它转换为一个含时区的offset-aware型:

In [22]: now=now.replace(tzinfo=pytz.timezone('UTC'))

In [23]: now
Out[23]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000, tzinfo=<UTC>)

In [24]: now.tzinfo
Out[24]: <UTC>

同样的,将一个offset-aware型转换为offset-naive型:

In [25]: now=now.replace(tzinfo=None)

In [26]: now
Out[26]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)

原文:https://blog.csdn.net/qq_25420115/article/details/53149669

posted @ 2021-01-22 17:26  久末丶  阅读(246)  评论(0编辑  收藏  举报