TrolliOlli TrolliOlli - 9 days ago 6
Python Question

Python format date of the form "Monday, January 1, 1991"

I'm creating a web scraper and I'm running into an issue where the date the website gives me is of the form "Monday, January 1, 1991"

What's the best way to format this into a "MM-DD-YYYY" format? Should I split on the comma, pull out the month and convert it to a number, and then put the numbers together? Or is there some quicker way to do this?

Answer

Use the datetime module, using strptime to parse to a datetime object, then strftime to format as you need it:

from datetime import datetime

date = datetime.strptime("Monday, January 1, 1991", "%A, %B %d, %Y")
print(date.strftime("%m-%d-%Y"))

which outputs:

01-01-1991

For the record, any time you're considering rolling your own parser, the answer is almost always "Don't". Rolling your own parser is error-prone; if at all possible, look for an existing parser.