简体   繁体   中英

Python Only If Time is 5 past the hour

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.

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')

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')

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM