-1

I need to define a function to get a [list] of str values of time from "M" minutes before the current time, up to the current time (including current time), and then check whether any of the values match the time value in the Time column of a given CSV file.

I thought of the idea for a for loop but could not figure out how to add and append the list for M no. of times (Quality of an Absolute Beginner). So, I adjusted with the following code which only supports M = 1 :

def Time_Check_Min(M= 1):
    #Check the current system time
    timestr = datetime.now()
    Check_TIMEnow = timestr.strftime("%H:%M")

    #Add 'M' min to Current Time
    Ahead_Time = (timestr + timedelta(minutes=M))
    Check_TIME = Ahead_Time.strftime("%H:%M")

    #Check if the current time is mentioned in the Dataframe
    if Check_TIME in df_.Time.values or Check_TIMEnow in df_.Time.values:
        return True
    else:
        return False

I require the output as a list in ('%H:%M') format so as to then check if any of them is present in the CSV. For Example, Taking the current system time to be '16:50' and M = 3 , then the list should contain 4 elements, like :

['16:47', '16:48', '16:49', '16:50']

Also, I thought of using the between time method since I am using pandas. But again, I do not know if this would really help.

Do I need to change my approach? If Yes, then which would be the best way to do so... and if not, HOW to get that damn list?

                    !! Thanks for your Time for these Time_Values !!   
PNxZEN
  • 51
  • 2
  • 6

2 Answers2

1

Not sure how you are defining your time period, but this will make a range from 25 minutes ago and test each minute in the format you need.

current_time = datetime.now()
minutes_prior =  25
start_time = current_time + timedelta(minutes=-minutes_prior))
#pd.date_range(start_time, current_time, freq="1min")

def Time_Check_Min(ttest):
    if ttest in df_.Time.values:
        return True
    else:
        return False

for t in pd.date_range(start_time, current_time, freq="1min"):
    print(t.strftime("%H:%M"))
    #Check if the current time is mentioned in the Dataframe
    Time_Check_Min(t.strftime("%H:%M"))
Jonathan Leon
  • 5,440
  • 2
  • 6
  • 14
  • hi. it is variable in that you can set it to what you want. i just chose 25 minutes. you can use minutes_prior = input('Enter number of minutes to test') or something similar – Jonathan Leon May 11 '21 at 01:57
  • Sorry, but the Question change was intended and I got confused ( Don't know why )‍♂️‍♂️ – PNxZEN May 11 '21 at 03:21
0

as you're using pandas we can do this with a pandas .date_range function and some handy list slicing.

from typing import Optional
import pandas as pd

def get_time_delta_range(time_value : str, M : Optional[int] = 1) -> list:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    return t_range[idx -M : idx + 1]

vals = get_time_delta_range('16:50', M=3)
print(vals)

['16:47', '16:48', '16:49', '16:50']

then use isin to filter your list.

df_['Time'].isin(vals)

edit.

def get_time_delta_range(dataframe : pd.DataFrame,
                         time_value : str, M : Optional[int] = 1) -> bool:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    t_range_slice = t_range[idx -M : idx + 1]
    return dataframe.isin(t_range_slice).sum().astype(bool)[0]

df = pd.DataFrame({'time' : ['16:04','16:05']})
get_time_delta_range(df,'16:04')
True

get_time_delta_range(df,'16:09')
False
Umar.H
  • 22,559
  • 7
  • 39
  • 74
  • BTW, May I know what's the role of the class "Optional" here ?? – PNxZEN May 11 '21 at 01:45
  • @PNxZEN don't use `if ...` these are standard python methods which don't apply to `pandas` easily. you can use the `isin` I provided above, Whats your end goal? `Optional` is just that, it just tells you that the argument is optional, it gives the user better and more readable arguments :) – Umar.H May 11 '21 at 02:35
  • Thanks, but I got it fixed... Let me show my goal... In a func : #Check if the current time is mentioned in the Dataframe **if df_['Time'].isin(vals).any() == True:** _return True_ **else:** _return False_ Any other efficient way to do it ?? – PNxZEN May 11 '21 at 02:39
  • @PNxZEN do you want to show it at a row by row level or if `one` value is in the dataframe just return a single output as `true` ? see my edited function that will return the sum of the true/false values in your dataframe, if there is one, it will return True, if None false. – Umar.H May 11 '21 at 02:42
  • @PNxZEN you can indeed, I think you have enough to go with to figure it out:) feel free to open a new question with your own research if you get stuck – Umar.H May 11 '21 at 02:57
  • Apologies for the reversed-up question before.... :( – PNxZEN May 11 '21 at 03:19