Good Morning,
I have the following Dataframe (Year, Month, Day, Hour, Sec):
print(df)
Date Price
2018-01-02 09:42:00 2
2018-01-02 09:46:00 4
2018-01-02 10:22:00 6
...
I would like to get, without minutes and seconds:
print(final_df)
Date Price
2018-01-02 2
2018-01-02 4
2018-01-02 6
...
I tried:
df['Date'] = datetime.datetime.strptime(df['Date'], '%Y-%m-%d').date()
But it reports "strptime() argument 1 must be str, not Series"
If not datetime column need to_datetime
with dt.date
:
print (df.dtypes)
Date object
Price int64
dtype: object
df['Date'] = pd.to_datetime(df['Date']).dt.date
print (df.dtypes)
Date object
Price int64
dtype: object
print (df['Date'].head().apply(type))
0 <class 'datetime.date'>
1 <class 'datetime.date'>
2 <class 'datetime.date'>
Name: Date, dtype: object
Or if need datetimes without hour
s, minute
s and second
s use dt.floor
:
df['Date'] = pd.to_datetime(df['Date']).dt.floor('d')
print (df.dtypes)
Date datetime64[ns]
Price int64
dtype: object
print (df['Date'].head().apply(type))
0 <class 'pandas._libs.tslibs.timestamps.Timesta...
1 <class 'pandas._libs.tslibs.timestamps.Timesta...
2 <class 'pandas._libs.tslibs.timestamps.Timesta...
Name: Date, dtype: object
If datetime column:
print (df.dtypes)
Date datetime64[ns]
Price int64
dtype: object
df['Date'] = df['Date'].dt.date
df['Date'] = df['Date'].dt.floor('d')
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