简体   繁体   English

仅在时间是凌晨5点之后才使用Python

[英]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. 我只想运行一段代码,如果时间在一个小时中的特定分钟之间,但是我不知道如何在Python中获得小时数。

The equivalent code in PHP is: PHP中的等效代码是:

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: 在Python中将是这样的:

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. 我通常会使用cron,但这是在Lambda内运行的,我想确保此代码不会一直运行。

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. datetime类具有可以使用的属性。 You are interested in the minute attribute . 您对minute属性感兴趣。

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: 这是一个避免加载datetime模块的衬里:

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). 上面的代码仅在小时(当然是当地时间)之后的5到15分钟之间运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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