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

how to convert a string containing characters into date time using strptime in Python

I’m trying to convert a string where there exists a characters between date information into a datetime. I was wondering if this is possible without using replace function. Suppose my string is defined as '20220117A1745' implying Jan. 17th, 2022 at 5:45pm.

If I use strptime, as expected, I receive an error.

from datetime import datetime
datetime.strptime(x,"%Y%m%d%H%M")
ValueError: unconverted data remains: A1745

I was wondering if I can do this without using another method. The reason why I don’t want to use antoher method is that, replace has a bad time ecomplexity and will slow the execution time badly (see for reference). I’ll do this operation for hundreds of thousans of strings in a for loop.

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

>Solution :

If the string always has ‘A’ in the same position then you can do this:

from datetime import datetime
x = '20220117A1745'
print(datetime.strptime(x,"%Y%m%dA%H%M"))

If you don’t know what the letter is then:

print(datetime.strptime(x[:8]+x[9:],"%Y%m%d%H%M"))

Output for both methods:

2022-01-17 17:45: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