[英]How to check for a "between 23:00 and 6:30" condition?
我想用arrow
(*)檢查當前時間是否在 23:00 和 6:30 之間。
我目前在下面的代碼中使用了簡單的檢查,但想知道是否有可用的arrow
本機構造
import arrow
def check(now):
if now.hour >= 23 or now.hour < 6 or (now.hour == 6 and now.minute <= 30):
print("we are between 23:00 and 6:30 the next day")
else:
print("we are outside the range")
#out
now = arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)
# in
now = arrow.get('2013-05-05 23:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)
# in
now = arrow.get('2013-05-06 01:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)
# in
now = arrow.get('2013-05-06 05:45:45', 'YYYY-MM-DD HH:mm:ss')
check(now)
# out
now = arrow.get('2013-05-06 07:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)
(*)我很高興使用arrow
多年,但如果使用另一個包( dolorean
或另一個類似的我忘記了名稱)的解決方案更簡單,那也很好
您可以使用默認的datetime
python 庫,但請記住,您必須堅持使用時區,如果您需要本地時間,我建議通過調用datetime.utcnow
或datetime.now
來使用 UTC。 下面是一個例子:
In [12]: from datetime import datetime
In [13]: now = datetime.utcnow()
In [14]: now.hour
Out[14]: 16
In [15]: 6 < now.hour < 23
Out[15]: True
附注。 如果由於某種原因datetime
時間不是一個選項,您可以使用arrow.utcnow()
或相同的本地化arrow.now()
變體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.