UTC是一种标准的时间表述方式,它与时区无关,用某一时刻与UNIX时间原点(1970年1月1日0时0分0秒),但对普通人来说不太适合.我们只会说早上8点而不会说离UTC时间15点还差7小时
所以需要UTC与当地时间之间进行转换
python提供了两种方式
1.time模块,有个名叫localtime的函数
import time
now = 1407694710
local_tuple = time.localtime(now)
time_format = '%Y-%m-%d %H:%M:%S'
time_str = time.strftime(time_format, local_tuple)
print(time_str)
time_tuple = time.strptime(time_str, time_format)
utc_now = time.mktime(time_tuple)
print(utc_now)
输出:
2014-08-11 02:18:30
1407694710.0
如果用时区的转换,手工管理很麻烦
import time
# now = 1407694710
# local_tuple = time.localtime(now)
time_format = '%Y-%m-%d %H:%M:%S'
# time_str = time.strftime(time_format, local_tuple)
# print(time_str)
#
# time_tuple = time.strptime(time_str, time_format)
# utc_now = time.mktime(time_tuple)
# print(utc_now)
parse_format = '%Y-%m-%d %H:%M:%S %Z'
depart_info = '2014-05-01 15:45:15 PDT'
time_tuple = time.strptime(depart_info, parse_format)
time_str = time.strftime(time_format, time_tuple)
print(time_str)
会报错,time模块的使用,最好是UTC时间和datetime模块之间的转换,其他类型,用datetime更好
2.datetime模块
from datetime import datetime, timezone
now = datetime(2014, 8, 10, 18, 18, 30)
# now = datetime.now()
now_utc = now.replace(tzinfo=timezone.utc)
now_local = now_utc.astimezone()
print(now_local)
输出:2014-08-11 02:18:30+08:00