python - 查找给定日期,月份和工作日名称的年份

时间:2018-03-23 22:35:20

标签: python datetime

我有一列字符串,可以将月份和日期命名为

Date      Week Day
03-03     Friday
03-19     Saturday
03-18     Saturday
03-18     Monday
....

我希望在最近的一年中回归,考虑到那些月份和日期,但也给出了当天的名字。

所以

Date     Week Day       Max Year
03-03    Friday         2018
03-19    Saturday       2016
03-18    Saturday       2017
03-18    Monday         2013
....
编辑:抱歉忘记添加我的想法并尝试

所以我尝试做类似的事情:

from datetime import datetime
day = 28
month = 3
name = 'Monday'
t = datetime.strptime('{}_{}_{}'.format(month,day,name), '%d_%m_%A')
t.strftime('%Y')

但它存储的年份为1900年。我只是不确定如何将它作为最新版本或maxyear返回年份?

1 个答案:

答案 0 :(得分:1)

据我所知,你必须写一个for循环来搜索最近一年。这显示了如何做到这一点的一个例子。

import datetime
today = datetime.date.today() # This would be the user input date
weekday = 1 # look for the most recent Tuesday on today's date
while(today.weekday() != weekday and today.year > 1000):
    today = today.replace(year=today.year - 1) # subtract one year from the date
    if today.weekday() == weekday:
        print("The Most recent Tuesday was in:",today.year)
        break

if today.year <= 1000:
    print("No Date found matching critieria since year 1000 AD")