python 处理时区问题, 解决运行环境的时区不正确导致的问题
- 使用timezone
from datetime import datetime,timedelta,timezone
time_format = "%Y-%m-%d %H:%M:%S"
tz = timezone(timedelta(hours=-8))
utc_time = '2024-05-07 15:37:51'
local_time = datetime.utcfromtimestamp(datetime.strptime(utc_time, time_format).replace(tzinfo=tz).timestamp()).strftime(time_format)
print(local_time)
- 自主加上偏移量
from datetime import datetime,timedelta
utc_time = '2024-05-07 15:37:51'
time_format = "%Y-%m-%d %H:%M:%S"
local_time = (datetime.strptime(utc_time, time_format) + timedelta(hours=8)).strftime(time_format)
print(local_time)