仅当时间是整点后 5 点时才使用 Python

标签 python date

我只想在时间在一小时内的特定分钟之间运行一段代码,但我不知道如何在 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/

相关文章:

python - 忽略 python 变量

Python 3 - 非复制流接口(interface)到 bytearray?

JavaScript:Date 的 toString() 和 toLocaleString() 方法之间的区别

r - 如何从日期中减去/添加天数?

python - 陷入无限循环

python - Python中离散变量的逆方法

Python 对 UbuntuOne 文件 api 的 urllib2/oauth2 请求返回 401 未授权错误

python - Pandas 按名称和最近日期合并

javascript - 在 jquery 中设置 &lt;input type ="date"... 的值

ios - 如何在不丢失格式的情况下将字符串转换为日期