I want to convert dates like these:
January 2022 -> 01-2022
February 2022 -> 02-2022
CodePudding user response:
month = {"january": "01", "february": "02", "march": "03", "april": "04", "may": "05", "june": "06", "july": "07", "august": "08", "september": "09", "october": "10", "november": "11", "december": "12"}
given = 'January 2022'
given = given.split(' ') #--> ['January','2022']
given[0] = month[given[0].lower()]
output = '-'.join(given)
print(output)
CodePudding user response:
You can use strptime
and strftime
from datetime.datetime
:
from datetime import datetime
input_dates = ["January 2022", "February 2022", "March 2022"]
[datetime.strftime(datetime.strptime(date, "%B %Y"), "%m-%Y") for date in input_dates]
# ['01-2022', '02-2022', '03-2022']