Python将UTC时间转化为Local时间
python 使用 sql 查询数据库,查询集中的 datetime 字段的值与数据库中的值 or 与本地时间相差 8 小时,解决这个问题的方式:
参考地址:https://blog.csdn.net/wuxianglong/article/details/7061568#
数据库中存放的时间为UTC时间,但是现在要求都出来显示的时间为本地时间
from dateutil import tz
from datetime import datetime
from_zone = tz.gettz('UTC') # UTC Zone
to_zone = tz.gettz('CST') # China Zone
例:
utc = datetime.utcnow()
utc = utc.replace(tzinfo=from_zone) # 实际应用中,这里将 utc 换成数据库查询集中对应的数据
local = utc.astimezone(to_zone)
local_time = datetime.strftime(local, "%Y-%m-%d %H:%M:%S")
or
local_time = local.strftime("%Y-%m-%d %H:%M:%S")