I have some values like '1967' and 'May 1976'. In python, how can I convert
1967
to 01-01-1967
and May 1976
to 05-01-1976
?
I have some values like '1967' and 'May 1976'. In python, how can I convert
1967
to 01-01-1967
and May 1976
to 05-01-1976
?
This works but idk if thats a good way.
import datetime
def year_to_date(year):
asdate = datetime.datetime.strptime(year, '%Y')
print(asdate.date())
def month_year_to_date(month_year):
asdate = datetime.datetime.strptime(month_year, '%B %Y')
print(asdate.date())
year_to_date("1967")
month_year_to_date("May 1967")
https://stackabuse.com/converting-strings-to-datetime-in-python/
makes a good explanation to this.
You can try the dateutil
library to parse your date strings.
Install with Pip:
pip install python-dateutil
Sample:
from dateutil import parser
date = parser.parse("May 1976")
print(date.strftime('%d-%m-%Y'))
This provides a lot of other functionalities as well which you can check out here in the documentation: https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse