I've got the following line of code
df['Sent Date'] = pd.to_datetime(df['Sent Date'], format = '%-m/%-d/%Y %-I:%M:%S %p')
trying to convert these sort of strings to datetime
1/1/2021 2:20:00 PM
I get the following error
'-' is a bad directive in format '%-m/%-d/%Y %-I:%M:%S %p'
Also tried
import datetime
df['Sent Date'] = datetime.strptime(df['Sent Date'], '%-m/%-d/%Y %-I:%M:%S %p')
and got the error
'module 'datetime' has no attribute 'strptime'
From viewing other questions/answers I thought one of these approaches would work ...
CodePudding user response:
The '-' is intended for output only (with strftime):
df['Sent Date'] = pd.to_datetime(df['Sent Date'], format='%m/%d/%Y %I:%M:%S %p')
print(df)
# Output
0 2021-01-01 14:20:00
Name: Sent Date, dtype: datetime64[ns]
Output:
>>> df['Sent Date'].dt.strftime('%-m/%-d/%Y %-I:%M:%S %p')
0 1/1/2021 2:20:00 PM
Name: Sent Date, dtype: object
Setup:
df = pd.DataFrame({'Sent Date': ['1/1/2021 2:20:00 PM']})
