我有四个变量:
start_hour = '12'
start_minute = '00'
end_hour = '22'
end_minute = '30'
从datetime:
current_hour = datetime.now().hour
curren_minute = datetime.now().minute
我想比较当前时间是否在范围内:
if int(start_hour) <= current_hour and int(end_hour) >= current_hour:
something
但是如何用分钟来实现呢?
答案 0 :(得分:13)
您可以使用datetime.timedelta
可靠地进行比较。您可以在不同的时间单位(小时,分钟,秒等)中指定增量。然后您不必担心明确转换为小时,分钟等。
例如,要检查当前时间是否超过<?php
$datetime = "2016-07-14 17:00:00";
$dt = new DateTime($datetime);
echo $dt->format('F jS Y \a\t g:ia');
?>
:
start_time
您还可以使用if abs(datetime.now() - start_time) > datetime.timedelta(hours=1):
# Do thing
将时间换一个给定的数量:
timedelta
除了单位之间的简单转换之外,six_point_five_hours_from_now = datetime.now() + datetime.timedelta(hours=6, minutes=30)
的好处是它会自动处理跨越多天的时差等。
答案 1 :(得分:7)
更好的方法是将两次转换为分钟:
start_time = int(start_hour)*60 + int(start_minute)
end_time = int(end_hour)*60 + int(end_minute)
current_time = datetime.now().hour*60 +datetime.now().minute
if start_time <= current_time and end_time >= current_time:
#doSomething
如果您需要包含秒数,请将所有内容转换为秒。
答案 2 :(得分:6)
怎么样:
>>> import datetime
>>> now = datetime.datetime.now()
>>> breakfast_time = now.replace( hour=7, minute=30, second=0, microsecond=0 )
>>> lunch_time = now.replace( hour=12, minute=30, second=0, microsecond=0 )
>>> coffee_break = now.replace( hour=16, minute=00, second=0, microsecond=0 )
>>> breakfast_time <= lunch_time <= coffee_break
True
答案 3 :(得分:2)
使用datetime
个对象完成所有操作的简单明了的方法是:
now = datetime.now()
start = now.replace(hour = int(start_hour), minute = int(start_minute))
end = now.replace(hour = int(end_hour), minute = int(end_minute))
if start <= now <= end:
print('something')