Datetime模块应用:Python计算上周周几对应的日期
我们希望有一个通用的解决方案能找出一周中上一次出现某天时的日期。比方说上周四是几月几号?
解决方案
Python的datetime模块中有一些实用函数和类可以帮助我们完成这样的计算。关于这个问题, 本人的设计源码如下:
from datetime import datetime, timedelta
weekdays = {
'周一': ('Monday', 0), '周二': ('Tuesday', 1), '周三': ('Wednesday', 2), '周四': ('Thursday', 3),
'周五': ('Friday', 4), '周六': ('Saturday', 5), '周日': ('Sunday', 6)}
def get_previous_byday(dayname, start_date=None):
if start_date == None:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays[dayname][1]
days_ago = (7 + day_num - day_num_target) % 7
if not days_ago:
days_ago = 7
if day_num <= day_num_target:
target_date = start_date - timedelta(days=days_ago)
else:
target_date = start_date - timedelta(days=days_ago) - timedelta(days=7)
return target_date
try:
weekday_name = input('请输入周几(周一,周二...)>>> ')
result = get_previous_byday(weekday_name)
day_to_str = str(result).split(' ')[0]
print('上{}的日期是 {}'.format(weekday_name, day_to_str))
except:
print('输入错误!!!')
运行结果如下:
D:\Python39\python.exe D:/My_Project/python_cook_book/计算上周5的日期.py
请输入周几(周一,周二...)>>> 周四
上周四的日期是 2023-05-04
Process finished with exit code 0
D:\Python39\python.exe D:/My_Project/python_cook_book/计算上周5的日期.py
请输入周几(周一,周二...)>>> 周一
上周一的日期是 2023-05-01
Process finished with exit code 0