Valueerror: Time Data Does Not Match Format When Parsing a Date

ValueError: time data does not match format '%H:%M:%S.%f' (match)

You have different options.

(1) Edit the text before parsing the date

from datetime import datetime

date_texts = [
"15:00:56.052554",
"02:43:10",
"05:46:12",
"23:15:14.5687"
]

for date_text in date_texts:
if not '.' in date_text:
date_text += ".0"
dt = datetime.strptime(date_text, "%H:%M:%S.%f")

print(f"{date_text} --> {dt}")

(2) Check the date format first, then apply the correct format when parsing

from datetime import datetime
import re

date_texts = [
"15:00:56.052554",
"02:43:10",
"05:46:12",
"23:15:14.5687"
]

for date_text in date_texts:
if re.match(r"^[0-9]+:[0-9]+:[0-9]+\.[0-9]+$", date_text):
dt = datetime.strptime(date_text, "%H:%M:%S.%f")
else:
dt = datetime.strptime(date_text, "%H:%M:%S")

print(f"{date_text} --> {dt}")

(3) Try the first format, catch the exception, then try the second format

from datetime import datetime

date_texts = [
"15:00:56.052554",
"02:43:10",
"05:46:12",
"23:15:14.5687"
]

for date_text in date_texts:
try:
dt = datetime.strptime(date_text, "%H:%M:%S.%f")
except ValueError:
dt = datetime.strptime(date_text, "%H:%M:%S")

print(f"{date_text} --> {dt}")

ValueError: time data does not match format '%y/%m/%d'

It is just a format error. I have attached the code with its solution. a date string '2021-12-18' is parsed by this function if the format given is '%Y-%m-%d'.
Code with the solution

time data does not match format

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)

time data does not match format (match)

There are two problems with your date format.


pd.to_datetime(dfbaseline['Date'], format='%d-%m-%yyyy %H:%M:%S')
^^^^^^^^
  • %m is used to match Month in a zero-padded decimal number
    format
    (01 to 12).
  • %y will match year without century as a zero-padded decimal number(00, 01, …, 99)

So you have to change,

  • %b to match Month in a locale’s abbreviated name(Jan/Feb/Mar etc)
  • %Y to match Year with century as a decimal number(0001, 0002, …, 2013, 2014, …, 9998, 9999)

pd.to_datetime(dfbaseline['Date'], format='%d-%b-%Y %H:%M:%S')
^^^^^

See strftime() and strptime() Format Codes for more information.

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

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')



Related Topics



Leave a reply



Submit