Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time data does not match format

I get the following error:

time data '07/28/2014 18:54:55.099000' does not match format '%d/%m/%Y %H:%M:%S.%f'

But I cannot see what parameter is wrong in %d/%m/%Y %H:%M:%S.%f ?

This is the code I use.

from datetime import datetime
time_value = datetime.strptime(csv_line[0] + '000', '%d/%m/%Y %H:%M:%S.%f')

I have added and removed the 000 but I get the same error.

like image 258
Stephane Rolland Avatar asked Jul 29 '14 12:07

Stephane Rolland


3 Answers

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)
like image 200
Martijn Pieters Avatar answered Oct 15 '22 10:10

Martijn Pieters


While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:

2-digit / 4-digit year

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

Infer the datetime automatically

If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True, for example:

yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)

Be advised that this solution is slower than using a pre-defined format.

like image 90
whiletrue Avatar answered Oct 15 '22 10:10

whiletrue


No need to use datetime library. Using the dateutil library there is no need of any format:

>>> from dateutil import parser
>>> s= '25 April, 2020, 2:50, pm, IST'
>>> parser.parse(s)
datetime.datetime(2020, 4, 25, 14, 50)
like image 19
Amit Kumar Avatar answered Oct 15 '22 10:10

Amit Kumar