user31735
user31735

Reputation: 113

Add year to date

I have a small issue with data cleaning. I have the date/month without the year and I want to add the year to it. I need to check if this date is from this year i.e. 2018 and if the month is January, February or March. If not check from 2017. My data is exactly from April 2017, hence I think this crude method will work, any suggestion will be appreciated. I have added my code but wondering if there is some nicer way to do this

Input: "15 March"
Desired output: "15 March 2018"

My code!

from datetime import date
from dateutil import parser
test = "15 March"
ico = parser.parse(test)
#print(ico.month)
today = date.today()
diff = abs(today.month - ico.month)
print(diff)
if diff <= 3:
  print(test + " 2018")
else:
  print(test + " 2017")

Upvotes: 2

Views: 157

Answers (1)

iam.Carrot
iam.Carrot

Reputation: 5276

You can simply keep the months in an array if you're sure about the months being in their full orientation.

>>> this_year = ['january', 'february', 'march']
>>> last_year = ['april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
>>> def add_year(input_date: str)-> str:
    month = input_date.split(' ')[-1]
        updated_date = f'{input_date} 2018' if month.lower() in this_year else f'{input_date} 2017'
    return updated_date

>>> add_year('25 march')
'25 march 2018'
>>> add_year('25 March')
'25 March 2018'

Upvotes: 3

Related Questions