Files
Python_CookBook_repo/3.数字日期和时间/13.计算上周五的日期.py
2025-09-10 16:12:45 +08:00

32 lines
945 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime, timedelta
if __name__ == '__main__':
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
def get_previous_by_day(day_name, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(day_name)
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
get_previous_by_day("Friday")
# 但是如果要经常这么干请使用dateutil包
d = datetime.now()
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
# 找最近的周五FR是rrule里的函数
print(d + relativedelta(weekday=FR))
# 找上一个周五
print(d + relativedelta(weekday=FR(-1)))