-2

I have a column of strings that give me month and day and day name as

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

I want to return the most recent year, given those months and days, but also given the name of day.

so

Date     Week Day       Max Year
03-03    Friday         2018
03-19    Saturday       2016
03-18    Saturday       2017
03-18    Monday         2013
....

EDIT: Sorry forgot to add what I was thinking and trying

So I'm trying to do something like:

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

But it stores year as 1900. I'm just not sure how to get it to return the year as the most recent, or maxyear?

chitown88
  • 27,527
  • 4
  • 30
  • 59
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service. http://idownvotedbecau.se/noattempt/ – Prune Mar 23 '18 at 22:41
  • Have a look at this question. It will help you get started - https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python – PrasadK Mar 23 '18 at 22:48

1 Answers1

1

As far as I know, you will have to write a for loop to search for the most recent year. This shows an example of how you can do that.

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")
digitaLink
  • 458
  • 3
  • 17
  • It works up until I try to do february 29. Because the input needs to include the year, if you do a year that's not a leap year, it'll return a ValueError. – chitown88 Mar 24 '18 at 02:14
  • Interesting, it looks like you will have to detect if it is a leap year somehow – digitaLink Mar 24 '18 at 02:22