timedelta类是datetime.py中的一个类,主要处理时间的计算
其结构如下:
#class datetime.datetime.timedelta(days=0, seconds=0, microseconds=0,milliseconds=0, minutes=0, hours=0, weeks=0)
生成时间差
#生成时间差 today = datetime.date.today() td = datetime.timedelta(10) # 10 days, 0:00:00 ,<class 'datetime.timedelta'> td = datetime.timedelta(days=-10) # -10 days, 0:00:00 <class 'datetime.timedelta'> td = datetime.timedelta(days=-10,hours=5) # -10 days, 5:00:00 <class 'datetime.timedelta'> td = datetime.timedelta(days=-10,hours=-5) # -11 days, 19:00:00 <class 'datetime.timedelta'> td = datetime.timedelta(days=-10,hours=-5,weeks=1) # -4 days, 19:00:00 <class 'datetime.timedelta'>
计算目标日期
#计算目标日期 #计算4天后 dt = datetime.date.today() # 2020-03-15 td = datetime.timedelta(days=4) print(dt + td)# 2020-03-19 #计算4小时前 dt = datetime.datetime.today() # 2022-03-15 11:25:28.309209 td = datetime.timedelta(hours=4) print(dt - td) # 2022-03-15 07:25:28.309209 #计算1周以后 dt = datetime.date.today() # 2020-03-15 td = datetime.timedelta(weeks=1) print(dt + td) # 2022-03-22
根据服务器时间,算本周时间段
from datetime import date, datetime, timedelta def this_monday(today): """ :function: 获取本周周一日期 :param_type: datetime :return: 返回周一的日期 :return_type: string """ td = timedelta(days = today.weekday()) return datetime.strftime(today - td, "%Y-%m-%d") def this_sunday(today): """ :function: 获取本周周日日期 :param_type : datetime :return: 返回周日日期 :return_type: string """ td = timedelta(days = 7-today.weekday()-1) return datetime.strftime(today + td, "%Y-%m-%d") today = date.today() print(this_monday(today)) print(this_sunday(today))