文章内容
2022/8/29 11:12:47,作 者: 黄兵
TypeError: can't subtract offset-naive and offset-aware datetimes
今天在计算两个时间相减的时候出现了如下错误:
TypeError: can't subtract offset-naive and offset-aware datetimes
出现错误的原因:
不能减去无偏移和有偏移的数据时间,下面是两个时间的样式:
结束时间:
end_time=datetime.strptime('2023-07-30T16:00:00.000Z', '%Y-%m-%dT%H:%M:%S.%f%z')
时间格式如下:
2023-07-30 16:00:00+00:00
开始时间:
time_now=datetime.utcnow()
时间格式如下:
2022-08-29 02:57:06.164710
由于结束时间带了时差,而开始时间没有带时差,所以会出现以上问题。
解决方案:
由于这里只需要计算相差月份,所以没有必要换算时差,直接去掉结束时间的时区就可以了,代码如下:
end_time=end_time.replace(tzinfo=None)
这样就去掉了时差,可以经行运算。
如果要求的时间比较精确,需要经行时区换算,之后再计算时间差。
参考资料:
1、Can't subtract offset-naive and offset-aware datetimes
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - TypeError: can't subtract offset-naive and offset-aware datetimes
PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider.
SQLAlchemy 如何向列增加注释
SQLAlchemy 如何向列增加注释
评论列表