Calculate the date of the last Friday
You need to find the last day of the week , Like Friday .
Python Of datetime There are tools, functions and classes in the module to help you perform such calculations . Here's a general solution to a problem like this ：
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
Use the following in the interactive interpreter ：
>>> datetime.today() # For reference datetime.datetime(2012, 8, 28, 22, 4, 30, 263076) >>> get_previous_byday('Monday') datetime.datetime(2012, 8, 27, 22, 3, 57, 29045) >>> get_previous_byday('Tuesday') # Previous week, not today datetime.datetime(2012, 8, 21, 22, 4, 12, 629771) >>> get_previous_byday('Friday') datetime.datetime(2012, 8, 24, 22, 5, 9, 911393) >>>
Optional start_date The parameter can be made by another datetime Examples to provide . such as ：
>>> get_previous_byday('Sunday', datetime(2012, 12, 21)) datetime.datetime(2012, 12, 16, 0, 0) >>>
The principle of the above algorithm is like this ： First, map the start date and target date to the position of the week array ( Monday's index is 0), Then it calculates how many days the target date will take to reach the start date through modular operation . Then subtract that time difference from the start date to get the result date .
If you're going to do a lot of date calculations like this , You'd better install a third party package python-dateutil Instead of . such as , Here's how to use dateutil Module relativedelta() Function performs the same calculation ：
from datetime import datetime from dateutil.relativedelta import relativedelta from dateutil.rrule import * d = datetime.now() print(d) 2012-12-23 16:31:52.718111 # Next Friday print(d + relativedelta(weekday=FR)) 2012-12-28 16:31:52.718111 >>> # Last Friday print(d + relativedelta(weekday=FR(-1))) 2012-12-21 16:31:52.718111 >>>