Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Minutes and Hours from Series

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"

like image 904
Alessandro Ceccarelli Avatar asked May 24 '18 07:05

Alessandro Ceccarelli


1 Answers

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 hours, minutes and seconds 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')
like image 96
jezrael Avatar answered Nov 03 '22 07:11

jezrael