Home > front end >  Python: ValueError raised when parsing a datetime string
Python: ValueError raised when parsing a datetime string

Time:03-25

The following ValueError is being raised while running the following code. The date is passed as a string from an another component, where I need to strip out the time.

ValueError: time data '2022-03-24T14:02:24.6413975' does not match format '%Y-%m-%d %H:%M:%S,%f'

The code:

from datetime import datetime
date='2022-03-24T14:02:24.6413975'
time = datetime.strptime(date, "%Y-%m-%d %H:%M:%S,%f")
if time > '09:30' :
  print("do some thing")

CodePudding user response:

The primary issue you're facing is the datetime format, as explained by the error message.

  • The .%f formatter can only accept six decimal places.
  • The T is missing from the format string.
  • There is a comma before the %f formatter, where there should be a full stop.

Therefore, this is the formatting string you need:

'%Y-%m-%dT%H:%M:%S.%f'

Additionally, time can be parsed from a datetime object simply by calling the .time() function as follows. String parsing should not be used, if at all possible.

time = dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f").time()

Next, the if statement should compare datetime object to datetime object, as:

if time > dt.time(9,30):
    ...

Therefore, the complete solution is as follows:

import datetime as dt

# Fractional seconds reduced to 6 decimal places.
date = '2022-03-24T14:02:24.641397'  
# Use the .time() function to extract the time.
time = dt.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f').time()
# Compare datetime object to datetime object.
if time > dt.time(9,30):
    print('Do some stuff ...')

CodePudding user response:

Hope this may help:

def stripTime():
    date='2022-03-24T14:02:24.6413975'
    date=date.split('T')
    print(date[1])
stripTime()

Output:

14:02:24.6413975

CodePudding user response:

This should work:

import datetime
date='2022-03-24T14:02:24.6413975'
time = date.split('T')[1].split(':')
time = datetime.time(int(time[0]), int(time[1]), int(time[2].split('.')[0]), int(time[2].split('.')[1][:6]))
if time > datetime.time(9, 30) :
    print("do some thing")

Output:

do some thing

This just takes date, splits it T, splits the second part of the resulting string at every :, and passes all of them to datetime.time. The last two arguments to datetime.time have to be split a the decimal to get the microseconds, and the last one has to be shortened because of the limit on how long datetime allows microseconds to be.

  • Related