简单举例datetime模块
from datetime import timedelta,datetimea = timedelta(days=2, hours=6)b = timedelta(hours=4.5)c=a+bprint(c) # 2 days, 10:30:00print(c.seconds) # 37800print(c.seconds/3600) # 10.5print(c.total_seconds()) # 210600.0
表示指定的日期和时间
d=datetime(2018,2,4)print(d) # 2018-02-04 00:00:00print(d+timedelta(days=5)) # 2018-02-09 00:00:00e=datetime(2018,3,4)print(e-d) # 28 days, 0:00:00# datetime 会自动处理闰年print((e-d).days) # 28
需要执行更加复杂的日期操作,比如处理时区,模糊时间范围,节假日计算等等, 可以考虑使用 dateutil模块
f= datetime(2019, 1, 23)# print(f+timedelta(months=1)) # 'months' is an invalid keyword argument for this functionfrom dateutil.relativedelta import relativedeltaprint(f+relativedelta(months=+1)) # 2019-02-23 00:00:00# dateutil.relativedelta() 函数有一点需要注意的就是,它会在处理月份(还有它们的天数差距)的时候填充间隙aa=datetime(2019,2,1)bb=datetime(2019,4,5)print(bb-aa) # 63 days, 0:00:00cc=relativedelta(bb,aa)print(cc) # relativedelta(months=+2, days=+4)print(cc.months) # 2print(cc.days) # 4
题目:计算最后一个周日的日期
通用解答:
from datetime import datetime, timedeltaweekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']def get_previous_byday(dayname, start_date=None): """ Topic: 最后的周日 Desc : """ if start_date is None: start_date = datetime.today() day_num = start_date.weekday() # 开始日期 day_num_target = weekdays.index(dayname) # 目标日期,星期一索引为0 print(day_num,day_num_target) # 4 6/0 6/4,6 days_ago = (7 + day_num - day_num_target) % 7 print(days_ago) # 5/1/5 if days_ago == 0: days_ago = 7 target_date = start_date - timedelta(days=days_ago) return target_datetarget_date=get_previous_byday('Sunday', datetime(2012, 12, 21)) # 星期日target_date=get_previous_byday('Sunday') # 2019-03-03 16:34:01.143620target_date=get_previous_byday('Sunday',datetime(2019, 3, 1)) # 2019-02-24 00:00:00print(target_date)
如果你要像这样执行大量的日期计算的话,你最好安装第三方包 python-dateutil 来代替
from dateutil.relativedelta import relativedeltafrom dateutil.rrule import *date=datetime.now()# Next Fridayprint(date+relativedelta(weekday=FR)) # 2019-03-08 17:29:57.376490# Last Fridayprint(date+relativedelta(weekday=FR(-1))) # 2019-03-01 17:30:44.357886