【Python】基于datetime工具函数:时间戳与格式化时间转换/时区转换

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值