Django
Django

Reputation: 67

convert 'July 31, 2021' to YYYY-MM-DD format caused ValueError: time data 'July 31, 2021' does not match format '%m %d, %Y'

I have a web app , using Django as backend. I used datetime.strptime function in python3 to convert the date to the format need to input to Mysql database. But I got the error: ValueError: time data 'July 31, 2021' does not match format '%m %d, %Y'

end_date = request.GET.getlist('end_date')[0]   # end_date = 'July 31, 2021' in the test case
end_date_converted = datetime.strptime(end_date, "%m %d, %Y").strftime("%Y-%m-%d")

How could I convert 'July 31, 2021' to YYYY-MM-DD format so I could save it to MYSQL date column?

Upvotes: 0

Views: 646

Answers (2)

dinesh kumar
dinesh kumar

Reputation: 95

replace %m with %B which will decode the Month full name

Upvotes: -1

Selcuk
Selcuk

Reputation: 59184

According to docs %m is "Month as a zero-padded decimal number", not the month name. You should be using

%B %d, %Y

as the format specifier. For example:

>>> datetime.strptime('July 31, 2021', '%B %d, %Y').strftime('%Y-%m-%d')
'2021-07-31'

Upvotes: 2

Related Questions