任務:
尋找上一個星期五的日期。python
解決方案:
經過python標準庫的datetime模塊,能夠快速完成此任務。測試
import datetime, calendar def find_last_Friday(): last_Friday = datetime.date.today() oneday = datetime.timedelta(days=1) while last_Friday.weekday() != calendar.FRIDAY: last_Friday -= oneday print(last_Friday)
測試結果:spa
任務:
給定兩個日期,計算這兩個日期之間隔了幾天。code
解決方案:ip
def calc_date_time(start_time,end_time): count = 0 oneday = datetime.timedelta(days=1) start_time = datetime.datetime.strptime(start_time,'%Y-%m-%d') end_time = datetime.datetime.strptime(end_time,'%Y-%m-%d') while start_time != end_time: start_time += oneday count += 1 return count
測試用例:it
if __name__ == '__main__': # find_last_Friday() start_time = '2018-05-07' end_time = '2018-06-01' print(calc_date_time(start_time,end_time))
測試結果:ast
討論:
此實現方法有一個bug,無法實現一年以上的計算會形成越界錯誤。此方法也有諸多限制,時間格式是固定的,計算量大時效率很低。class