要将一周中的某一天作为int,我们使用datetime.datetime.today().weekday()
;要从datetime中减去days,我们使用datetime.today() - timedelta(days=days_to_subtract)
,现在我们可以制作一个字典,将一周中的某一天与要减去的天数联系起来,并使用该字典进行减法:
from datetime import datetime, timedelta
d = {0:3,1:4,2:5,3:6,4:0,5:1,6:2}
lastfriday = datetime.today()-timedelta(days=d[datetime.today().weekday()])
也可以让他自动计算字典值
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 4) % 7
friday = today - timedelta(days=offset)
print(friday)
来源
https://stackoverflow.com/questions/68477122/how-to-get-last-fridays-date-with-python
https://www.pythonprogramming.in/how-to-get-last-friday-in-python.html
标签:timedelta,Python,friday,days,datetime,星期五,日期,import,today From: https://www.cnblogs.com/yuyanc/p/16891487.html