文章内容
2021/8/11 17:56:41,作 者: 黄兵
Python UTC 时间运算
最近需要计算 UTC 时间,过去 n 个小时的时间,下面是具体代码:
get_different_utc = datetime.utcnow() - timedelta(hours=6)
例如:现在是 2021年10月7日 10:00 则减去6小时后是 2021年10月7日 4:00。
这里首先获取的是当前的 UTC 时间,之后通过 timedelta
设置时间间隔是6小时,关于 timedelta
可以查看参考资料。
timedelta
对象表示两个 date 或者 time 的时间间隔。
当然可以计算其他许多时差:
get_different_utc = datetime.utcnow() - timedelta(days=1, hours=6, minutes=5)
上面计算了当前 UTC 1天6小时5分钟的时差,当然也可以计算以后的时差,例如:
get_different_utc = datetime.utcnow() - timedelta(days=-2, hours=-1, minutes=-15)
这里计算了当前 UTC 时间,2天1小时15分钟后的时间。
如果时区不同,需要转换时区,具体可以参考这篇文章:python 时区计算时差
项目里最重要的是:时间需要统一,不能存储的是+8时区,但是换算使用的 UTC 时间,这样会存在问题,需要时间换算,非常麻烦。
参考资料:
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - Python UTC 时间运算
AttributeError: 'sqlalchemy.cimmutabledict.immutabledict' object has no attribute 'setdefault'
Python ipaddress 相关操作
Python ipaddress 相关操作
评论列表