????????from datetime import datetime, timedelta, date
????????fmt:指定日期字符串的格式,其中%Y表示四位年份,%m表示两位月份,%d表示两位日
?
date_str = "2022-01-01"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)
# 输出:2022-01-01 00:00:00
date_obj = datetime(2022, 1, 1)
date_str = date_obj.strftime("%Y-%m-%d")
print(date_str)
# 输出:2022-01-01
????????????????timedelta是datetime模块中的一个类,用于表示时间间隔(即时间差)。它可以用来进行时间的加减运算,并且可以表示不同单位的时间差,如天、小时、分钟。常用于对天的处理,例如前一天、后一天等。
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
from datetime import datetime, timedelta, date
delta = timedelta(days=1)
print(delta)
# 输出: 1 day, 0:00:00
date_obj = datetime(2022, 1, 1)
previous_day = date_obj - timedelta(days=1)
next_day = date_obj + timedelta(days=1)
print(previous_day)
print(next_day)
# 输出:
# 2021-12-31 00:00:00
# 2022-01-02 00:00:00
????????relativedelta是dateutil库中的一个类,用于计算两个日期之间的差距,并且可以实现灵活的日期运算。relativedelta相比timedelta更为灵活,可以实现更复杂的日期运算,如计算两个日期之间的年数、月数、星期数等。
????????dateutil属于第三方库,需要安装后才能使用。
from dateutil.relativedelta import relativedelta
relativedelta(years=0, months=0, days=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0)
date_obj = datetime(2022, 1, 1)
previous_month = date_obj - relativedelta(months=1)
next_month = date_obj + relativedelta(months=1)
print(previous_month)
print(next_month)
# 输出
# 2021-12-01 00:00:00
# 2022-02-01 00:00:00
????????博主也总结了自己常用的几个功能,封装成了函数,供大家参考使用
????????分别是三个功能:拆分年月日时分秒、拆分年月日、获取两个时间间隔的日期列表
from datetime import datetime, timedelta
from ProjectStart.set_logger import USE_LOGGER
# 拆分为年月日 与 时分秒
def handle_date_and_time(start_time, end_time, fmt='%Y-%m-%d %H:%M:%S'):
"""
将传入的开始和结束时间,转为字符串拆分成【年月日】 与 【时分秒】
:param start_time: 开始日期
:param end_time: 结束日期
:param fmt: 对应的日期格式
:return: 返回拆分后的值
"""
data_dict = {'data': "", "warning_info": "", "error_info": "", }
try:
# 获取拆分后的时间格式
if isinstance(start_time, str) and isinstance(end_time, str):
start_date_str = start_time.split(" ")[0]
start_time_str = start_time.split(" ")[-1]
end_date_str = end_time.split(" ")[0]
end_time_str = end_time.split(" ")[-1]
elif isinstance(start_time, datetime) and isinstance(end_time, datetime):
try:
start_date_str = datetime.strftime(start_time, fmt).split(" ")[0]
start_time_str = datetime.strftime(start_time, fmt).split(" ")[-1]
end_date_str = datetime.strftime(end_time, fmt).split(" ")[0]
end_time_str = datetime.strftime(end_time, fmt).split(" ")[-1]
except ValueError:
data_dict["error_info"] = "日期类型格式转换失败"
return data_dict
else:
data_dict["error_info"] = "数据类型不一致"
return data_dict
data_dict["data"] = start_date_str, start_time_str, end_date_str, end_time_str
except Exception as e:
USE_LOGGER.exception(e)
finally:
return data_dict
# 拆分日 日期
def split_day_time(start_time, end_time, whole_fmt='%Y-%m-%d %H:%M:%S', date_fmt='%Y-%m-%d', split_day=1):
"""
按照指定拆分的日间隔,拆分为列表
:param start_time: 开始日期
:param end_time: 结束日期
:param whole_fmt: 对应的整个日期格式
:param date_fmt: 对应日的日期格式
:param split_day: 拆分的间隔
:return: 返回嵌套列表,每一个子列表为固定时间间隔的值
"""
data_dict = {'data': "", "warning_info": "", "error_info": "", }
ever_date_list = []
handle_result_dict = handle_date_and_time(start_time, end_time, fmt=whole_fmt)
if handle_result_dict["error_info"]: return
start_date_str, start_time_str, end_date_str, end_time_str = handle_result_dict["data"]
if start_date_str == start_time_str or end_date_str == end_time_str:
start_time_str = ""
end_time_str = ""
try:
ever_date = datetime.strptime(start_date_str, date_fmt).date()
end_date = datetime.strptime(end_date_str, date_fmt).date()
if ever_date == end_date:
ever_date_list.append([f"{ever_date} {start_time_str}" if start_time_str else f"{ever_date}",
f"{ever_date} {end_time_str}" if end_time_str else f"{ever_date}"])
else:
while ever_date < end_date:
new_start_date = f"{ever_date} {start_time_str}" if start_time_str else f"{ever_date}"
ever_date += timedelta(days=split_day)
ever_date = ever_date
new_end_date = f"{ever_date} {end_time_str}" if end_time_str else f"{ever_date}"
ever_date_list.append([new_start_date, new_end_date])
data_dict["data"] = ever_date_list
except ValueError:
data_dict["error_info"] = "日期类型格式转换失败"
return data_dict
finally:
return data_dict
# 获取每一天时间列表
def get_day_date_list(start_time, end_time, whole_fmt='%Y-%m-%d', date_fmt='%Y-%m-%d', out_fmt='%Y-%m-%d'):
data_dict = {'data': "", "warning_info": "", "error_info": "", }
day_date_list = []
handle_result_dict = handle_date_and_time(start_time, end_time, fmt=whole_fmt)
if handle_result_dict["error_info"]: return
try:
start_date_str, start_time_str, end_date_str, end_time_str = handle_result_dict["data"]
start_date = datetime.strptime(start_date_str, date_fmt).date()
end_date = datetime.strptime(end_date_str, date_fmt).date()
delta = end_date - start_date
# 生成每一天的日期并添加到列表中
for i in range(delta.days + 1):
date = start_date + timedelta(days=i)
day_date_list.append(date.strftime(out_fmt))
data_dict["data"] = day_date_list
except ValueError:
data_dict["error_info"] = "日期类型格式转换失败"
return data_dict
finally:
return data_dict
if __name__ == '__main__':
# s_time = "2024-01-09 00:00:00"
# e_time = "2024-01-12 00:00:00"
# w_fmt = '%Y-%m-%d %H:%M:%S'
# d_fmt = '%Y-%m-%d'
s_time = "2024-01-09"
e_time = "2024-01-20"
w_fmt = '%Y-%m-%d'
d_fmt = '%Y-%m-%d'
result = split_day_time(s_time, e_time, w_fmt, d_fmt)
print(result)