第一の方法:
Python代码
from datetime import datetime, timedelta
weekdays = ['月曜日', '火曜日', '水曜日', '木曜日',
'金曜日', '土曜日','日曜日']
def get_previous_byday(dayname, start_date=None):
start_date が None の場合:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(曜日名)
days_ago = (7 + day_num - day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date - time delta(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)))