user10821857
user10821857

Reputation:

ValueError: time data does not match format when parsing a date

When I try to parse a string to a datetime, I do this (having imported datetime before):

fecha_2 = datetime.strptime('22/01/2019 17:00', '%d/%m/%y %H:%M')

However, I receive this error

ValueError: time data '22/01/2019 17:00' does not match format '%d/%m/%y %H:%M'

anyone know why?

Upvotes: 1

Views: 10221

Answers (3)

to240
to240

Reputation: 381

The above is correct. However, to avoid these kind of errors you can use dateutil.parser, which can automatically guess the correct format string. You can install it by doing pip install python-dateutil

>>> from dateutil import parser
>>> parser.parse("2018-06-19 11:21:13.311")
datetime.datetime(2018, 6, 19, 11, 21, 13, 311000)

Upvotes: 2

wpercy
wpercy

Reputation: 10090

You need to use a capital Y for a 4 digit year (lowercase y is for a 2 digit year like 19). So:

>>> fecha_2 = datetime.strptime('22/01/2019 17:00', '%d/%m/%Y %H:%M')
>>> fecha_2
datetime.datetime(2019, 1, 22, 17, 0)

strptime docs

Upvotes: 2

Glazbee
Glazbee

Reputation: 648

The y should be capitalized. This is referenced in the Python docs found here

This works fine

fecha_2 = datetime.strptime('22/01/2019 17:00', '%d/%m/%Y %H:%M')

Upvotes: 5

Related Questions