如何从单个代码中获取=>最近的星期五,上周的星期五,上周的第二个星期五,最后的第三个星期三,第n个的星期三的日期?

时间:2020-07-23 18:01:56

标签: python datetime

如何获取日期=>最近的星期五,上周的星期五,上周的第二个星期五,最后一个星期三的星期五,最后一个星期三的星期五?

2 个答案:

答案 0 :(得分:0)

another question获取此信息,您可以使用dateutil库:

from datetime import datetime
from dateutil.relativedelta import relativedelta, FR
lastfriday = datetime.now() + relativedelta(weekday=FR(-1))
print(lastfriday) # lastfriday is a datetime element, do anything with it

获得第二个最后一个-2,获得第三个-3,依此类推

答案 1 :(得分:0)

如果没有dateutil,则可以这样操作:

import datetime
import calendar

now = datetime.datetime.now()

dow = now.weekday()

print('Today is {0}, {1}.'.format(calendar.day_name[dow], now.strftime('%m/%d/%y')))

# Find the nearest Monday.
monday = -dow if dow < 4 else 7-dow

# Use the previous week's Friday if today is a Friday.
friday = 4 - (7 if dow == 4 else 0)

last_friday = (now + datetime.timedelta(days=monday+friday, weeks=-1)) 

print('The date last Friday was {0}.'.format(last_friday.strftime('%m/%d/%y')))

for weeks_ago in range(2, 5):
    last_friday = (now + datetime.timedelta(days=monday+friday, weeks=-weeks_ago)) 
    print('The date {0} Fridays ago was {1}.'.format(weeks_ago, last_friday.strftime('%m/%d/%y')))