Python3 日期与时间戳相互转换

开发中常常会对时间格式处理,对于时间数据,好比2019-02-28 10:23:29,有时须要日期与时间戳进行相互转换,在Python3中主要用到time模块,相关的函数以下:数组

其中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

复制代码

 

不管从事什么行业,只要作好两件事就够了,一个是你的专业、一个是你的人品,专业决定了你的存在,人品决定了你的人脉,剩下的就是坚持,用善良專業和真诚赢取更多的信任。unix

相关文章
相关标签/搜索