strptime unconverted data remains

554 Views Asked by At

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?

2

There are 2 best solutions below

0
jezrael On BEST ANSWER

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
0
Matmozaur On

the problem is with your date value, as there is no such hour as 24. If your string will be correct, as e.g.: '31-12-2022:12' it should be ok.