M. Sprout
M. Sprout

Reputation: 45

Datetime formatting in Python does not match format

I have a date stored in a string as:

date = '26 March 2018'

I'm trying to convert it to a datetime object with the following code:

date_element2 = datetime.strptime(date, '%d, %B, %Y')

But I'm getting the following traceback error:

ValueError: time data '26 March 2018' does not match format '%d, %B, %Y'

I can't figure out for the life of me how the formatting is incorrect, any help would be appreciated.

Thanks,

Upvotes: 0

Views: 1352

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48110

You need to remove comma , from the format string, then it should work. For example:

>>> from datetime import datetime
>>> date = '26 March 2018'

#                              v  v  No comma here
>>> datetime.strptime(date, '%d %B %Y')
datetime.datetime(2018, 3, 26, 0, 0)

Upvotes: 2

Related Questions