I'm using the following code to convert strings in a dataframe column to datetime and add 60 days for each row.
pd.to_datetime(df['datetime_string'], format="%Y-%m-%dT%H:%M:%S.%fZ") + timedelta(days=60)
Due to the fact that I load data from an external API and write it in df['datetime_string']
, I receive different data like:
"2023-11-24T09:34:18Z"
"2023-11-24T09:35:19.130122Z"
so sometimes I don't have the milliseconds part in the string.
Which leads to a ValueError: time data "2023-11-24T09:34:18Z" doesn't match format "%Y-%m-%dT%H:%M:%S.%fZ"
I want to fill the missing milliseconds part with .000000 and always have the %Y-%m-%dT%H:%M:%S.%fZ
format.
What is the best way to do this especially when dealing with huge data ?
First add a millisecond to the datetime, then convert again with the required format: