1. 导入time库
import time
2. 格式化时间 转 时间戳
# 格式化时间 ===> 时间戳
def conver_to_timestamp(time_value): # "2023-07-22 00:00:00"
timeArray = time.strptime(time_value, "%Y-%m-%d %H:%M:%S") # 转换成时间数组
# print(timeArray) # time.struct_time(tm_year=2023, tm_mon=7, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=203, tm_isdst=-1)
timestamp = int(time.mktime(timeArray)) # 转换成时间戳
return timestamp # 1689955200
t1 = "2023-07-22 00:00:00"
time_str = conver_to_timestamp(t1)
print(f"time_str : {time_str} {type(time_str)}")
# 输出结果为:
# time_str : 1689955200 <class 'int'>
3. 时间戳 转 格式化时间
# 时间戳 ===> 格式化时间
def conver_to_timeformat(timestamp): # 1689955200
timeArray = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
return timeArray # 2023-07-22 00:00:00
time_str = 1689955200
time_format = conver_to_timeformat(time_str)
print(f"time_format : {time_format} {type(time_format)}")
# 输出结果为:
# time_format : 2023-07-22 00:00:00 <class 'str'>
4. 全部代码
import time
# 格式化时间 ===> 时间戳
def conver_to_timestamp(time_value): # "2023-07-22 00:00:00"
timeArray = time.strptime(time_value, "%Y-%m-%d %H:%M:%S") # 转换成时间数组
# print(timeArray) # time.struct_time(tm_year=2023, tm_mon=7, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=203, tm_isdst=-1)
timestamp = int(time.mktime(timeArray)) # 转换成时间戳
return timestamp # 1689955200
t1 = "2023-07-22 00:00:00"
time_str = conver_to_timestamp(t1)
print(f"time_str : {time_str} {type(time_str)}")
# 输出结果为:
# time_str : 1689955200 <class 'int'>
# 时间戳 ===> 格式化时间
def conver_to_timeformat(timestamp): # 1689955200
timeArray = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
return timeArray # 2023-07-22 00:00:00
time_str = 1689955200
time_format = conver_to_timeformat(time_str)
print(f"time_format : {time_format} {type(time_format)}")
# 输出结果为:
# time_format : 2023-07-22 00:00:00 <class 'str'>