user2769952
user2769952

Reputation: 83

Python Nomarlizing Date Giving a Format

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

Upvotes: 0

Views: 132

Answers (2)

theWellHopeErr
theWellHopeErr

Reputation: 1872

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

Upvotes: 1

Ben
Ben

Reputation: 5087

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()

Upvotes: 0

Related Questions