Search code examples
pythonpandasdatetimetimestamputc

Failing to convert string do datetime pandas


I'm trying to perform de following operation:

pd.to_datetime('2023-05-02 11:52:09.000000 UTC', format='%Y-%m-%dT%H:%M:%S.%f')

But i'm getting the error: time data 2023-05-02 11:52:09.000000 UTC doesn't match format specified

Does anybody know how can I fix it?


Solution

  • As @mozway correctely pointed out in the comment to your question, you can write just

    pd.to_datetime('2023-05-02 11:52:09.000000 UTC')
    

    and pandas corretely convert your date. If you want to write this more explicitly, you can do this

    pd.to_datetime('2023-05-02 11:52:09.000000', format='%Y-%m-%dT%H:%M:%S.%f', utc=True)
    

    or this

    pd.to_datetime('2023-05-02 11:52:09.000000 UTC', format='%Y-%m-%d %H:%M:%S.%f %Z')
    

    All these expressions give the same result.