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) #
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
上一篇:JS 日期与时间戳相互转化


下一篇:insert into