Python – Time data does not match format

Time data does not match format… here is a solution to the problem.

Time data does not match format

My date format is similar to Apr 9 2018 and I want to convert it to something like 2018-04-19

My sample code looks like this:

datetime.strptime(unformated_date, '%m %d %y').strftime('%y-%m-%d') where unformated_date=”Apr 9 2018"

But I get the error time data 'Apr 9 2018' does not match format '%m %d %y'

How do I implement this in python? Thanks in advance

Solution

Your date string is "%b %d %Y"

For example:

import datetime
unformated_date = "Apr 9 2018"    
print( datetime.datetime.strptime(unformated_date, "%b %d %Y").strftime('%y-%m-%d') )
print( datetime.datetime.strptime(unformated_date, "%b %d %Y").strftime('%Y-%m-%d') )

Output:

18-04-09
2018-04-09

MoreInfo

Related Problems and Solutions