0

I am using datetime.strptime() to convert a string containing time and date from a sensor into a datetime object.

The code sometimes fails. Minimal example:

datetime.strptime('1/9/2021 24:01:53', '%d/%m/%Y %H:%M:%S')

Output error:

ValueError: time data '1/9/2021 24:01:53' does not match format '%d/%m/%Y %H:%M:%S'

I am guessing this has to do with the fact that the time is more than 23:59:59 - which seems to me a non-realistic time (I would think that 1/9/2021 24:01:53 could potentially be 2/9/2021 00:01:53 - a time format which I have never seen).

Is this a non-standard way of representing time or possibly a hardware/software issue with the sensor acquisition system? If it is a different way of representing time, how can I convert it to a standard datetime object?

Kind regards,

D.F.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
DanielFD
  • 3
  • 2
  • You can just substitute ` 24:` to ` 00:` before doing the conversion. Are you sure that 24:01:01 is the 2/9?. AFAIK also in case of 1-24h, the day changes at 24:00:00. – Giacomo Catenazzi Sep 14 '21 at 12:30
  • datetime.strptime('1/9/2021 24:00:00', '%d/%m/%Y %H:%M:%S') also produces an error - so I think that is also not standard (day will change at 00:00:00). Not sure if '1/9/2021 24:01:53' is 1/9 or 2/9, and that's why I am posting the question to try to clarify whether this could be a hardware/software issue with the sensor or a time format I am not familiar with. – DanielFD Sep 14 '21 at 12:34
  • There are two convention: 1 to 24 and 0 to 23 (and sometime 24:00:00 is allowed on the later format). So I think it is valid. Just I do not find good way to use the first format. – Giacomo Catenazzi Sep 14 '21 at 13:46

1 Answers1

0

If the hour exceeds 23 in a variable representing time, a good option is to create a timedelta from it, which you can then add to a datetime object. For given example that might look like

from datetime import datetime, timedelta

def custom_todatetime(s):
    """
    split date/time string formatted as 'DD/MM/YYYY hh:mm:ss' into date and time parts.
    parse date part to datetime and add time part as timedelta.
    """
    parts = s.split(' ')
    seconds = sum(int(x) * 60 ** i for i, x in enumerate(reversed(parts[1].split(':'))))
    return datetime.strptime(parts[0], "%d/%m/%Y") + timedelta(seconds=seconds)

s = '1/9/2021 24:01:53'
print(custom_todatetime(s))
# 2021-09-02 00:01:53

Note: conversion of hh:mm:ss to seconds taken from here - give a +1 there if helpful.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72