Search code examples
pythondatetimestrptime

What is the fastest they to convert string to DateTime (python)?


I've got a dataframe with id and date columns, date is a string:

df = pd.DataFrame([[0, '2020-03-26T15:37:19.765000Z'], [1, '2019-03-25T15:37:18Z'], [2, '2020-03-26T15:37:19.765000Z']], columns = ['id', 'date'])

I must convert date into DateTime for further working. I could find only one solution, with for loop.

for i in range(len(df)):
    if (len(df.loc[i, 'date']) != 27): 
       df.loc[i, 'date'] = df.date[i].replace('Z', '.000000Z')

for i in range(len(df)):
    df.loc[i, 'date'] = datetime.strptime(str(df.date[i]), '%Y-%m-%dT%H:%M:%S.%fZ')

It works as I need, but if df is large, it's unacceptably slow. Any suggestions?


Solution

  • as you are using pandas so you can easily do this by using to_datetime() method:-

    df['date']=pandas.to_datetime(df['date'])