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 an irregular string into a timestamp?

I feel like I am missing something obvious here so I would very much appreciate some help. Essentially, I have a df with a datetime column that is structured as below:

     datetime

0    2022.11.02D12:00:00.155132514
1    2022.11.02D12:00:00.999495094
2    2022.11.02D12:00:01.013525376
     ...

I am just wondering how I am able to convert this string into a timestamp format that Python can read and process as datetime. I have tried: df['datetime'] = pd.Timestamp(df['datetime']) but in doing so I am hit with the following error:

TypeError: Cannot convert input ... of type <class 'pandas.core.series.Series'> to Timestamp

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

I feel like I just need to add more arguments to the Timestamp function but the documentation is sadly unclear of what the syntax would look like.

Any help would be greatly appreciated 🙂

>Solution :

This works:

import pandas as pd
test_df = pd.DataFrame(
    [
        "2022.11.02D12:00:00.155132514",
        "2022.11.02D12:00:00.999495094",
        "2022.11.02D12:00:01.013525376"
    ], columns=["time"]
)
    

pd.to_datetime(test_df.time.str.replace("D","T"))

Output:

0   2022-11-02 12:00:00.155132514
1   2022-11-02 12:00:00.999495094
2   2022-11-02 12:00:01.013525376
Name: time, dtype: datetime64[ns]
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