第一种方法:
python代码
from datetime import datetime, timedelta
weekdays = [‘monday’,’tuesday’,’wednesday’,’thursday’,
‘friday’,’saturday’,’sunday’]
def get_previous_byday(dayname, start_date=none):
if start_date is none:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(dayname)
days_ago = (7 + day_num – day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date – timedelta(days = days_ago)
return target_date
print( datetime.today() )
print( get_previous_byday(‘monday’) )
print( get_previous_byday(‘monday’, datetime(2016, 8, 28)) )
第二种方法,用dateutil模块
python代码
from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
d = datetime.now()
print(d)
print(d + relativedelta(weekday=fr))
print(d + relativedelta(weekday=fr(-1)))