Home > other >  How to convert an irregular string into a timestamp?
How to convert an irregular string into a timestamp?

Time:11-03

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

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 :)

CodePudding user response:

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]
  • Related