修复 TypeError: can‘t compare offset-naive and offset-aware datetimes
offset-naive是无时区的类型,offset-aware是有时区类型。
如何判断是 offset-naive 还是 offset-aware?
- 通过 tzinfo 可以查看是哪种类型,如 datetime.now().tzinfo 返回 None,是 offset-naive 类型。
- 直接打印,有加号的,如 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)