1

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?

Tom
  • 109
  • 9
  • 4
    Hour cannot be `24`: [Docs](https://docs.python.org/3/library/datetime.html#datetime.datetime.hour). Use a string split since you only care about the date anyway. – ivvija May 02 '23 at 07:21
  • 2
    https://stackoverflow.com/questions/61052483/valueerror-unconverted-data-remains-4 – Panda Kim May 02 '23 at 07:25
  • Question edited, my mistake, I care about the hour too. Thanks – Tom May 02 '23 at 07:29

2 Answers2

2

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

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.

Matmozaur
  • 283
  • 2
  • 6