pandasstring-to-datetime

Conversion "Optional(2023-12-19 23:11:57 +0000)" to_datetime


I have some problems with conversing this one(object type) to datetime "Optional(2023-12-19 23:11:57 +0000)".

I need to get 2023-12-19 23:11:57 from that.

I tried df['start_time'] = pd.to_datetime(df['start_time']) and got:

ParserError: Unknown string format: Optional(2022-06-02 20:26:53 +0000) present at position 0

And also tried df['start_time'] = pd.to_datetime(df['start_time'], format='Optional') and got:

ValueError: unconverted data remains: (2022-06-02 20:26:53 +0000)

Solution

  • Try with the full format 'Optional(%Y-%m-%d %H:%M:%S %z)':

    df['start_time'] = pd.to_datetime(df['start_time'], format='Optional(%Y-%m-%d %H:%M:%S %z)')
    print(df)
    
    # Output
                     start_time
    0 2023-12-19 23:11:57+00:00
    

    Input:

    >>> df
                                start_time
    0  Optional(2023-12-19 23:11:57 +0000)