在时间处理上,有时候需要将日期改变为当前UTC标准时间或者其他时区的时间, 我们就需要用到pyzt模块
如何知道时区的名称
我们可以使用pytz.country_timezones,返回一个字典,可以使用ISO 3166国家代码
作为key来查询,比如我们要查中国时间,可以像下面这样:
>>> import pytz
>>>
>>>
>>> pytz.country_timezones['CN']
['Asia/Shanghai', 'Asia/Urumqi']
以上就返回了上海和乌鲁木齐的时区名称
获取UTC标准时间
from pytz import timezone, utc, country_timezones
# ============================================================================
# = get UTC time
# ============================================================================
def utcTime(date_time=None):
central = timezone('Asia/Shanghai')
local_d = datetime.now() if date_time == None else central.localize(date_time)
utc_d = local_d.astimezone(utc)
return utc_d
以上方法,utcTime方法的参数date_time为datetime.datetime类型,如果不写参数的话,默认使用当前的上海时间,转换为UTC 0时区的标准时间,我们使用testcase执行一下结果为:
def test_utc(self):
utc_time = utcTime()
print(str(utc_time))
self.assertIsInstance(utc_time, datetime, msg="return is not a datetime")
执行结果如下,2021-09-08 02:19:25.512137+00:00
即为UTC标准时间
转换为具体时区的标准时间
我们在上面代码的基础上增加了如下方法,zoneTime,提供时区的名称和date_time,如果date_time不提供则默认为当前时间
# ============================================================================
# = get dict for country_timezones
# ============================================================================
def zoneTime(countryTimeZone, date_time:datetime):
date_time = datetime.now() if date_time == None else date_time
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
validTimeZones = flatten(list(country_timezones.values()))
if countryTimeZone in validTimeZones:
zone_time = date_time.astimezone(timezone(countryTimeZone))
return zone_time
else:
raise Exception("country time zone is not valid")
我们使用testcase执行一下
# @unittest.skip
def test_contryZoneTime(self):
St_Kitts_zoneTime = zoneTime('America/St_Kitts', datetime.now())
print(St_Kitts_zoneTime)
self.assertIsInstance(St_Kitts_zoneTime, datetime, msg="St_Kitts_zoneTime is not valid")
结果如下,返回了-4时区的圣基茨和尼维斯联邦
时间
此网站https://www.zeitverschiebung.net/cn/timezone可以查询不同时区时间,以比较代码执行的结果
ISO 3166国家代码
可参考此链接: https://blog.csdn.net/qq_16393511/article/details/92794742