0

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?

nick_rinaldi
  • 641
  • 6
  • 17
  • Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – FObersteiner Jan 14 '22 at 16:40
  • => e.g. with [strptime and strftime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior). – FObersteiner Jan 14 '22 at 16:41

2 Answers2

1

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.

Sven s
  • 32
  • 3
0

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