Search code examples
pythonpandasdatetimestrptime

strptime unconverted data remains


I have a string I want to convert to a datetime in the following format:

'31-12-2022:24'

The last two digits being the hour. I tried the following to convert it:

dt = datetime.strptime(z[1], '%d-%m-%Y:%H').date()

But get the following error:

ValueError: unconverted data remains: 4

Why is it only selecting the first digit? I have a workaround, splitting the string and converting them separately before rejoining them but I'd like to just do it in one line.

What I would ideally like is a datetime object that allows me to do some maths on the difference between two dates (edit* and times), which I assume is easiest in datetime format?


Solution

  • You can split values and hours convert to timedeltas, because 24H is not valid for %H:

    z = '31-12-2022:24'
    
    a,b = z.split(':')
    
    dt = pd.to_datetime(a, format='%d-%m-%Y') + pd.to_timedelta(int(b), unit='H')
    print (dt)
    2023-01-01 00:00:00