How to deal with 24 hour time values ​​in python?

I am dealing with a lot of data that have both meanings and times (in rows).

I will convert string time values ​​to datetime values ​​with the following code:

time = datetime.datetime.strptime(time, " %H:%M:%S.%f")

The only problem is that some of my data has the format: 24: 00: 00.004.
Thus, some data is actually more than 24 hours

Python gives me this error: ValueError: time data "24: 00: 00: 004" does not match the format "% H:% M:% S.% f '

Any ideas on how to deal with this problem

+5
source share
3 answers

%H 0-23. :

try:
     time = datetime.datetime.strptime(time, " %H:%M:%S.%f")
except ValueError:
     time = time.replace(' 24', ' 23')
     time = datetime.datetime.strptime(time, " %H:%M:%S.%f")
     time += datetime.timedelta(hours=1)
+8

:

hours, rest = time.split(':', 1)
time = datetime.timedelta(hours=int(hours)) + datetime.datetime.strptime(rest, "%M:%S.%f")
+2

It looks like your data does not contain dates, but the time spans, so you should store your data as timedeltainstead datetime.


You can use this function to create timedeltafrom your lines:

import re
from datetime import timedelta

def parseTimeDelta(s):
    d = re.match(
            r'((?P<days>\d+) days, )?(?P<hours>\d+):'
            r'(?P<minutes>\d+):(?P<seconds>\d+)\.(?P<milliseconds>\d+)',
            str(s)).groupdict(0)
    return timedelta(**dict(( (key, int(value))
                              for key, value in d.items() )))

Parse your timeline '24:00:00.004'like this

→> t = parseTimeDelta ('24: 00: 00.04 ')

will result in a timedelta presented like this

→> print t
1 day, 0: 00: 00.004000

+1
source

All Articles