import datetime
def timeswitch(t,sourcetz = "utc",totype="str",targettz = "cn",strformat = "%Y-%m-%d %H:%M:%S"):
'''
t: int/str 需要转换的时间表示,秒级时间戳或格式化的字符串
sourcetz: t所关联的时区别名,在timezone字典里自定义别名,如“cn”表示东八区,"utc"为世界标准时间
targettz: 输出时间的时区别名
totype: "str" or "timestamp" 输出时间表示类型
strformat:输入或输出的字符串格式,如果t为字符串,则strformat需要和它对应。
'''
# 常用的两个时区定义在字典里,可以添加其他时区
timezone = {
"cn":datetime.timezone(datetime.timedelta(hours=8)),
"utc":datetime.timezone.utc
}
sourcetz = timezone.get(sourcetz) if sourcetz else None
targettz = timezone.get(targettz) if targettz else sourcetz
# transfer to datetime
if isinstance(t,str):
ctime = datetime.datetime.strptime(t,strformat).replace(tzinfo = sourcetz)
elif isinstance(t,int) or isinstance(t,float):
if t > 1e10: t=t/1000
ctime = datetime.datetime.fromtimestamp(t).replace(tzinfo = sourcetz)
# from datetime to target type
if totype == "str":
newtime = ctime.astimezone(targettz).strftime(strformat)
elif totype == 'timestamp':
newtime = ctime.astimezone(targettz).timestamp()
newtime = int(newtime)
return newtime
示例:
# 时间戳转字符串 UTC时间换算北京时间
t1 = datetime.datetime.now().timestamp() #北京时间18点多在机器上取的时间
st1 = timeswitch(t1,sourcetz="utc",targettz="cn",totype='str')
print("st1:",st1)
# st1: 2021-06-16 18:54:31
# 字符串转时间戳 北京时区不变
st2 = timeswitch("2021-06-06 20:16:42",sourcetz="cn",targettz="cn",totype='timestamp')
print("st2:",st2)
# st2: 1622981802
# 字符串-》字符串, 转换时区
st3 = timeswitch("2021-06-16 18:58:42",sourcetz="cn",targettz="utc",totype='str')
print("st3:",st3)
# st3: 2021-06-16 10:58:42