温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python3中怎么实现日期与时间戳的相互转换

发布时间:2021-06-15 13:57:37 来源:亿速云 阅读:181 作者:Leah 栏目:大数据

Python3中怎么实现日期与时间戳的相互转换,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

其中unix_time函数是正常时间转unix时间戳,date_time是unix时间转正常时间如年月日时分秒:

import time

"""
日期转时间戳
"""


def unix_time(dt):
    # 转换成时间数组
    timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    # 转换成时间戳
    timestamp = int(time.mktime(timeArray))
    return timestamp


"""
时间戳转日期
"""


def custom_time(timestamp):
    # 转换成localtime
    time_local = time.localtime(timestamp)
    # 转换成新的时间格式(2016-05-05 20:28:54)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    return dt


time_now = '2019-02-28 10:23:29'
unix_t = unix_time(time_now)
custom_t = custom_time(unix_t)
print(unix_t)  # 1551320609
print(custom_t)  # 2019-02-28 10:23:29

# 如果是自定义的时间格式转换呢,思路方法雷同,比如下:
"""
时间用指定格式显示,比如 年-月-日 转 年/月/日
"""
dt = "2020-10-10 22:20:20"
# 转为数组
timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
# 转为其它显示格式
customTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(customTime)  # 2020/10/10 22:20:20

"""
时间用指定格式显示,比如 年/月/日 转 年-月-日
"""
dt = "2020/10/10 22:20:20"
timeArray = time.strptime(dt, "%Y/%m/%d %H:%M:%S")
customTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(customTime)  # 2020-10-10 22:20:20

看完上述内容,你们掌握Python3中怎么实现日期与时间戳的相互转换的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI