我只想在时间在一小时内的特定分钟之间运行一段代码,但我不知道如何在 Python 中获取小时数。
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
}
在 Python 中,它会是这样的:
import time
from datetime import date
if date.fromtimestamp(time.time()):
run_my_code()
else:
print('Not running my code')
我通常会使用 cron,但它在 Lambda 内运行,我想绝对确保此代码不会一直运行。
最佳答案
这是一种方法。
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')
关于仅当时间是整点后 5 点时才使用 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50306223/