簡單舉例datetime模塊
from datetime import timedelta,datetime a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c=a+b print(c) # 2 days, 10:30:00 print(c.seconds) # 37800 print(c.seconds/3600) # 10.5 print(c.total_seconds()) # 210600.0
表示指定的日期和時間
d=datetime(2018,2,4) print(d) # 2018-02-04 00:00:00 print(d+timedelta(days=5)) # 2018-02-09 00:00:00 e=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 function from dateutil.relativedelta import relativedelta print(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:00 cc=relativedelta(bb,aa) print(cc) # relativedelta(months=+2, days=+4) print(cc.months) # 2 print(cc.days) # 4
題目:計算最后一個周日的日期
通用解答:
from datetime import datetime, timedelta weekdays = ['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_date target_date=get_previous_byday('Sunday', datetime(2012, 12, 21)) # 星期日 target_date=get_previous_byday('Sunday') # 2019-03-03 16:34:01.143620 target_date=get_previous_byday('Sunday',datetime(2019, 3, 1)) # 2019-02-24 00:00:00 print(target_date)
如果你要像這樣執行大量的日期計算的話,你最好安裝第三方包 python-dateutil 來代替
from dateutil.relativedelta import relativedelta from dateutil.rrule import * date=datetime.now() # Next Friday print(date+relativedelta(weekday=FR)) # 2019-03-08 17:29:57.376490 # Last Friday print(date+relativedelta(weekday=FR(-1))) # 2019-03-01 17:30:44.357886
