Reputation:
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
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
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)
Upvotes: 2