2

I have the following strings that I'd like to convert to datetime objects:

'01-01-16 7:43'
'01-01-16 3:24'

However, when I try to use strptime it always results in a does not match format error.

Pandas to_datetime function nicely handles the automatic conversion, but I'd like to solve it with the datetime library as well.

format_ = '%m-%d-%Y %H:%M'

my_date = datetime.strptime("01-01-16 4:51", format_)

ValueError: time data '01-01-16 4:51' does not match format '%m-%d-%Y %H:%M'

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
hk_03
  • 192
  • 3
  • 12

2 Answers2

3

as i see your date time string '01-01-16 7:43'

its a 2-digit year not 4-digit year

that in order to parse through a 2-digit year, e.g. '16' rather than '2016', a %y is required instead of a %Y.

you can do that like this

from datetime import datetime
datetime_str = '01-01-16 7:43' 
datetime_object = datetime.strptime(datetime_str, '%m-%d-%y %H:%M')    
print(type(datetime_object))
print(datetime_object)  

give you output 2016-01-01 07:43:00

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
1

First of all, if you want to match 2016 you should write %Y while for 16 you should write %y.

That means you should write:

format_ = '%m-%d-%y %H:%M'

Check this link for all format codes.

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Catalina Chircu
  • 1,506
  • 2
  • 8
  • 19