Deleting times in a dataframe based on the current time

Viewed 49

I have the following data frame denoted by dfm.

My aim is to eliminate the rows with the time within 2.5hrs of the current time.

time A year time2 new_column dateTime
0 06/0818:00 32 21/ 21/06/0818:00 2021-06-08 18:00:00 18:00:00
1 06/0819:00 6 21/ 21/06/0819:00 2021-06-08 19:00:00 19:00:00
2 06/0920:00 5 21/ 21/06/0920:00 2021-06-09 20:00:00 20:00:00
3 06/0921:00 6 21/ 21/06/0921:00 2021-06-09 21:00:00 21:00:00
4 06/0922:00 41 21/ 21/06/0922:00 2021-06-09 22:00:00 22:00:00
5 06/0923:00 41 21/ 21/06/0923:00 2021-06-09 23:00:00 23:00:00
6 06/0900:00 38 21/ 21/06/0900:00 2021-06-09 00:00:00 00:00:00
7 06/0901:00 37 21/ 21/06/0901:00 2021-06-09 01:00:00 01:00:00

I started off by making sure new_column was a datetime rather than an object using:

pd.to_datetime(dfm['new_column'])
dfm.dtypes

which returned the type datetime64[ns] for new_column

I then ran the following code to denote the current time:

import datetime;

ct = datetime.datetime.now()
t = print("current time:-", ct)

The next part I'm having trouble with is creating a code that uses the current time to eliminate any times that are within 2.5hrs of the current time.

2 Answers

First thing, change ct into pd.datetime. I am not certain about the compatibility between python datetime and pandas datetime. You can basically filter after that.

For instance, code I use for changing now into pd.datetime is:

from datetime import date, timedelta
now = datetime.datetime.now()
date = [now]
df_today = pd.DataFrame(data=date)
df_today.columns = ['date']
df_today['date'] = pd.to_datetime(df_today['date'])
ct = df_today.iloc[0,0]

and then filter out what you want using similar syntax as below:

dfm = dfm[dfm['new_column'] <= ct + timedelta(hours=2.5)]
dfm = dfm[dfm['new_column'] >= ct - timedelta(hours=2.5)]

I would try something like

time_range = datetime.timedelta(hours=2.5)
dfm.drop(dfm.index([dfm['time'] < ct - time_range]))
dfm.drop(dfm.index([dfm['time'] < ct + time_range]))
Related