to_datetime vs to_pydatetime trying to convert str to datetime

Viewed 530

I have a DataFrame with one columns that is a date and a time and is a string. The format of the date and time is like this: 4/27/2021 12:39 This is what I have so far to try and convert the string into a datetime:

new_list = []
for i in range(len(open_times)):
    date = df.iloc[i]['Open Datetime']
    good_date = date.to_datetime()
    # good_date = date.topydatetime()
    new_list.append(good_date)

I have used to_pydatetime() in the past however the string was in a different format. When I run the code from above I get this error: AttributeError: 'str' object has no attribute 'to_datetime' and I get the same error when I run the commented out line except with to_pydatetime. Any thoughts on how to resolve this error? I think that this is happening because the format of the string is different than it typically is.

1 Answers

You need to use datetime.strptime(date_string, format) to convert a string to datetime type

from datetime import datetime

for i in range(len(open_times)):
    date = df.iloc[i]['Open Datetime']
    good_date = datetime.strptime(date, '%m/%d/%Y %H:%M')

But you could use pd.to_datetime directly

df['Open Datetime'] = pd.to_datetime(df['Open Datetime'])

# Convert a column to list
new_list = df['Open Datetime'].values.tolist()
Related