Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if time is within a certain minute?

Tags:

python

I want to write a simple python script which will check to see if it's 2 minutes before a given hour/minute, and then call my function either everyday or for a given date at the given time.

The script will run every minute in a cronjob.

So the two cases to execute myfunction():

10:55 everyday
10:55 on 9/28/2012

But I am having trouble determining when it's 2 minutes prior to the given hour/minute using datetime. Also, how to determine everyday vs just on a given day?

mydate = datetime(2012, 09,28, 10,55)
check = mydate - datetime.now()    # gives you a timedelta

if check < datetime.timedelta(minutes=2):
     run_myfunction()

The above sees if it's within 2 minutes, and if it is, then runs the myfunction(). The problem with the above code is that if the mydate has passed, the myfunction() will still run. Also, this requires that a specific date to be specified. How would one allow the check for everyday rather than 9/28/2012?

like image 935
4 revs Avatar asked Sep 18 '12 19:09

4 revs


People also ask

How do you check if time is within a certain range in Python?

How do you check if time is within a certain range in Python? Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.

How do I get the current time in python?

To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.

How do I get the hour of the day in Python?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.


1 Answers

now = datetime.now()
mystart = now.replace(hour=10, minute=55, second=0)
myend = mystart + timedelta(minutes=2)
if mystart <= mydate < myend:
    # do your stuff
like image 120
Mark Ransom Avatar answered Oct 12 '22 20:10

Mark Ransom