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.
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)
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:
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
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With