2

I only want to run a piece of code if the time is between specific minutes in an hour but I can't figure out how to get the hour number in Python.

The equivalent code in PHP is:

if (intval(date('i', time())) > 15 && intval(date('i', time())) < 32) {
    // any time from hour:16 to hour:33, inclusive
} else {
    // any time until hour:15 or from hour:32
}

In Python it would be something like this:

import time
from datetime import date
if date.fromtimestamp(time.time()):
   run_my_code()
else:
   print('Not running my code')

I'd typically use cron but this is running inside a Lambda and I want to make absolutely sure this code does NOT get run all the time.

Ken J
  • 877
  • 12
  • 21
  • 3
    Possible duplicate of [How to get current time in python and break up into year, month, day, hour, minute?](https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu) – David Zemens May 12 '18 at 12:34

3 Answers3

1

Here is one wasy of doing it.

import datetime

# Get date time and convert to a string
time_now = datetime.datetime.now().strftime("%S")    
mins = int(time_now)

# run the if statement
if mins > 10 and mins < 50:
    print(mins, 'In Range')
else:
    print(mins, 'Out of Range')
johnashu
  • 2,167
  • 4
  • 19
  • 44
  • 1
    This is quite an inefficient method of getting the 'minutes' field - 1) format time as a string - HH-MM-SS, 2) retrieve a substring containing only the minutes - why specify the others if you don't want them? 3) parse the string and convert to integer. – Attie May 12 '18 at 18:09
1

The datetime class has attributes that you can use. You are interested in the minute attribute.

For example:

from datetime import datetime

minute = datetime.now().minute

if minute > 15 and minute < 32:
    run_my_code()
else:
    print('Not running my code')
Attie
  • 6,690
  • 2
  • 24
  • 34
1

Here's a one liner that avoids loading the datetime module:

if 5 < int(time.strftime('%M')) < 15:

The above code will only run between 5 and 15 minutes past the hour (local time of course).

SurpriseDog
  • 462
  • 8
  • 18