I have a column that is a Series and I want to convert to a datetime format. This particular column of my data frame looks like below:
x
Aug 1, 2019 7:20:04 AM
Aug 1, 2019 7:20:14 AM
Aug 1, 2019 7:20:24 AM
Aug 1, 2019 7:20:34 AM
I've seem some answers here and I tried to adapt my code accordingly.
datetime.datetime.strptime(df["x"],'%b %d, %Y %H:%M:%S %a').strftime('%d/%m/%Y %H:%M:%S')
But I get the following error:
strptime() argument 1 must be str, not Series
For this reason, I tried to convert to string using the following:
df['x'] = df['x'].apply(str)
df['x'] = df['x'].to_string()
df['x'] = df['x'].astype(str)
But it does not work.
I am assuming you are using pandas. You can use pandas to_datetime() function instead of datetimes functions which can only convert a single value for a given call. Also for AM/PM you need %p instead of %a
df['x'] = pd.to_datetime(df['x'], format="%b %d, %Y %H:%M:%S %p")
Edit
Check to make sure your data is exactly how you posted it. I copy and pasted your data, and created a data frame and it works without an error.
df = pd.DataFrame({'x':['Aug 1, 2019 7:20:04 AM','Aug 1, 2019 7:20:14 AM','Aug 1, 2019 7:20:24 AM','Aug 1, 2019 7:20:34 AM']})
Output:
x
0 Aug 1, 2019 7:20:04 AM
1 Aug 1, 2019 7:20:14 AM
2 Aug 1, 2019 7:20:24 AM
3 Aug 1, 2019 7:20:34 AM
df['x'] = pd.to_datetime(df['x'],format='%b %d, %Y %H:%M:%S %p')
Output:
x
0 2019-08-01 07:20:04
1 2019-08-01 07:20:14
2 2019-08-01 07:20:24
3 2019-08-01 07:20:34
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With