0

So if several date strings with different formats and am looking for a way to normalize dates given the format.

For example, if I have three sets of date strings and their associated format strings:

date = 11/20/2020, format = MM/DD/YYYY

date = 11-20-2020, format = MM-DD-YYYY

date = 20-11-2020, format = DD-MM-YYYY

I am looking to normalize all of these dates into the format of YYYY-MM. Is there a way I can normalize the date if I am giving the format? Can the datetime package help here?

Nice to have: If there is a way to take in other types of dates too (ex: UTC format), that would be helpful as well

What I have so far is this:

date_list = re.split(r'\W+', date)
date_format_list = re.split(r'\W+', format)

year_index = date_format_list.index('YYYY')
month_index = date_format_list.index('MM')

formatted_year = date_list[year_index]
formatted_month = date_list[month_index]

'-'.join([formatted_year, formatted_month])

Update I am not able to change the format string which is causing the issue

  • 1
    Does this answer your question? [Normalize different date data into single format in Python](https://stackoverflow.com/questions/33051147/normalize-different-date-data-into-single-format-in-python) – etch_45 Nov 20 '20 at 17:44
  • 1
    If the answer solves your issue don't forget to accept that answer and close the issue. – kaceva5618 Nov 21 '20 at 03:20

2 Answers2

1

The strptime method in the datetime package can be used. You have to give the date as a string in the first parameter followed by the format of the date.

from datetime import datetime
date = datetime.strptime('11/20/2020', '%m/%d/%Y')
print(str_time)

You also have the strftime method which will compare a date object with the format and do the same.

date = datetime.strftime(date_obj, '%Y-%m-%d')

You can find the difference between them here

theWellHopeErr
  • 1,856
  • 7
  • 22
0

Yes, the datetime package contains what you need. You'll need to review the package docs and create a format string that matches each of your formats, but this is the idea

from datetime import datetime
date_str = '11/20/2020'
format_str = '%m/%d/%Y'
date = datetime.strptime(date_str, '%m/%d/%Y')
date.isoformat()
Ben
  • 4,980
  • 3
  • 43
  • 84