Loading

修复 TypeError: can‘t compare offset-naive and offset-aware datetimes

offset-naive是无时区的类型,offset-aware是有时区类型。

如何判断是 offset-naive 还是 offset-aware?

  1. 通过 tzinfo 可以查看是哪种类型,如 datetime.now().tzinfo 返回 None,是 offset-naive 类型。
  2. 直接打印,有加号的,如 2023-09-12 08:00:00+00:00 是 offset-aware 类型,没有则是 offset-naive

备注:datetime.utcnow()、datetime.now() 返回的是 offset-naive(无时区类型)

两个类型相互转换:

对于 offset-naive 转 offset-aware:

from datetime import datetime, timezone
import pytz
from zoneinfo import ZoneInfo

now = datetime.utcnow()
now1 = now.replace(tzinfo=timezone.utc)
now2 = now.replace(tzinfo=ZoneInfo('UTC'))
now3 = now.replace(tzinfo=pytz.timezone('UTC'))

对于 offset-aware 转 offset-naive:

now1 = now.replace(tzinfo=None)
posted @ 2024-07-03 11:28  Convict  阅读(36)  评论(0编辑  收藏  举报