关于时区的整理

Posted by Sky丶Memory on March 14, 2019

时区

平常开发中,接触时区、时间格式还是比较常见的,这里简单整理下:

UTC(Coordinated Universal Time): 世界协调时间时

CST(China Standard Time):中国标准时间

ISO时间格式为YYYY-MM-DDThh:mm:ss.sTZD,例如:1997-07-16T19:20:30.45+01:00,ISO时间格式中若带有Z,则表示UTC时间,带+hh:mm或-hh:mm表示时区偏移,为本地化时间,本地化时间减去时区偏移即可得UTC时间

时间一般不携带时区信息,所以需要将时间本地化,以Python为例:

# -*- coding: utf-8 -*-
import time

import pytz
import datetime

TIMEZONE = 'Asia/Shanghai'

# 本地化时间
local = pytz.timezone(TIMEZONE).localize(datetime.datetime.now())

print(local)

# 不同时区转换
other = local.astimezone(pytz.utc)

print(other)

# 国家对应时区名称
print(pytz.country_timezones)

# 时间戳转对应时区
ts = time.time()
dt = datetime.datetime.fromtimestamp(ts, pytz.timezone(TIMEZONE))

在Python中,不带时区信息的时间称为naive time,带时区信息的时间称为aware time