Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading