赞
踩
使用python
中的time
模块,对时间的几种格式进行转换
strptime()
, 将 时间字符串 转换成 结构化时间 struct_time
注意,结构化时间 是所有转换的 过渡格式
import time
time_str = "2022-03-18 10:54:00"
struct_time = time.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print(struct_time)
time.struct_time(tm_year=2022, tm_mon=3, tm_mday=18, tm_hour=10, tm_min=54, tm_sec=0, tm_wday=4, tm_yday=77, tm_isdst=-1)
struct_time 是一个类,里面分别对应了时间的年、月、日、时、分、秒、一周的第几天(周一是0,0-6)、一年的第几天(从1开始,1-366)、夏时令(是夏时令1,不是0,不知道-1)。
mktime()
,将 结构化时间 转换为 时间戳timestamp = time.mktime(struct_time)
print(timestamp)
1647572040.0
strftime()
,把 结构化时间 转换为 任意格式的时间字符串time_str_new = time.strftime("%Y%m%d-%H:%M:%S", struct_time)
print(time_str_new)
20220318-10:54:00
print(time.time())
print(time.localtime())
print(time.localtime(time.time()))
1647574078.38
time.struct_time(tm_year=2022, tm_mon=3, tm_mday=18, tm_hour=11, tm_min=27, tm_sec=58, tm_wday=4, tm_yday=77, tm_isdst=0)
time.struct_time(tm_year=2022, tm_mon=3, tm_mday=18, tm_hour=11, tm_min=27, tm_sec=58, tm_wday=4, tm_yday=77, tm_isdst=0)
时间戳 => 结构化时间 (struct_time) => 时间字符串
time_stamp = 1640844000
# 时间戳 => 结构化时间 => 时间字符串
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_stamp))
print(time_str)
2021-12-30 14:00:00
时间字符串 => 结构化时间 (struct_time) => 时间戳
time_str = "2022-03-18 10:54:00"
time_stamp = time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S'))
print(time_stamp)
1647572040.0
时间字符串A => 结构化时间 (struct_time) => 时间字符串B
time_str = "2022-03-18 10:54:00"
time_str_new = time.strftime("%Y%m%d-%H:%M:%S", time.strptime(time_str, '%Y-%m-%d %H:%M:%S'))
print(time_str_new)
20220318-10:54:00
import datetime
start_date = "20230801"
end_date = "20230805"
date_list = [datetime.datetime.strftime(datetime.datetime.strptime(start_date, "%Y%m%d") + datetime.timedelta(days=i), "%Y%m%d") for i in range((datetime.datetime.strptime(end_date, "%Y%m%d") - datetime.datetime.strptime(start_date, "%Y%m%d")).days + 1)]
print date_list
['20230801', '20230802', '20230803', '20230804', '20230805']
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。