how to pass a hours/minutes/datatime as input for a function in python

Viewed 117

I want to pass as input of my function a data time in order to select a precise time range to create a time mask. At the moment, I've tried this way

#name is the column where the data are

def mask (hour1, hour2, min1,min2, data1, data2, name):
   timemask=(
   (pd.Timestamp(data1).date() >= df[name].dt.date) &\
    (df[name].dt.date <= pd.Timestamp(data2).date()) &

   (df[name].dt.hour >= hour1) & (df[name].dt.minute >= min1) &\
           (df[name].dt.hour < hour2) & (df[name].dt.minute < min2)
   )
   df1=df[timemask]
   return df1

but it's not working and I don't know if I'm passing the values correctly.

1 Answers

As you can see in the following example, you need to convert your time column to pandas datetime format with df['col1'] = pd.to_datetime(df['col1']), in this case I named it col1 but you would write your time column name.

In the mask function, 4 dates are created; 2 for date checking and other 2 for time checking. The last 2 need to use the replace function to insert the input parameters of the mask function. Essentially, the function is traversing the time column with a for loop because the important result here is the timemask list of booleans, so with a for you will have access to each value:

import pandas as pd
from datetime import datetime
import random

datelist = pd.date_range(datetime.today(), periods=100).tolist()
hourlist = [f"{random.randint(0, 24)}:{random.randint(0, 60)}" for i in range(100)]

def mask (hour1, hour2, min1,min2, data1, data2, name):
   data1 = datetime.strptime(data1, '%Y-%m-%d')
   data2 = datetime.strptime(data2, '%Y-%m-%d')

   timemask = []
   for i in df[name]:
      data3, data4 = i, i
      data3 = data3.replace(hour=hour1, minute=min1, second=0)
      data4 = data4.replace(hour=hour2, minute=min2, second=0)

      if ((i > data1 and i <= data2) and (i > data3 and i <= data4)):
         timemask.append(True)
      else:
         timemask.append(False)

   df1=df.loc[timemask]
   return df1

df = pd.DataFrame({'col1': datelist, 'col2': hourlist, 'col3': list(range(100))})
df['col1'] = pd.to_datetime(df['col1'])

print(df, "\n")
print(mask(10, 21, 0, 40, "2022-04-30", "2022-05-05", "col1"))
Related