Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare hours and minutes?

Tags:

python

I have four variables:

start_hour = '12'
start_minute = '00'
end_hour = '22'
end_minute = '30'

and from datetime:

current_hour = datetime.now().hour
curren_minute = datetime.now().minute

And I want to compare if the current time is within the range:

if int(start_hour) <= current_hour and int(end_hour) >= current_hour:
    something

But how to implement this with minutes?

like image 341
Nips Avatar asked Jul 25 '16 20:07

Nips


People also ask

How do you compare hours in Python?

You can use datetime. timedelta to do the comparisons reliably. You can specify a delta in different units of time (hours, minutes, seconds, etc.) Then you don't have to worry about converting to hours, minutes, etc.

What does DateTime compare do?

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.


2 Answers

You can use datetime.timedelta to do the comparisons reliably. You can specify a delta in different units of time (hours, minutes, seconds, etc.) Then you don't have to worry about converting to hours, minutes, etc. explicitly.

For example, to check if the current time is more than an hour from the start_time:

if abs(datetime.now() - start_time) > datetime.timedelta(hours=1):
    # Do thing 

You can also use timedelta to shift a time by a given amount:

six_point_five_hours_from_now = datetime.now() + datetime.timedelta(hours=6, minutes=30)

The nice thing about timedelta apart from easy conversions between units is it will automatically handle time differences that span multiple days, etc.

like image 134
Suever Avatar answered Nov 10 '22 10:11

Suever


A much better way to go about this would beto convert both times to minutes:

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

If you need to include seconds, convert everything to seconds.

like image 24
Vaibhav Bajaj Avatar answered Nov 10 '22 10:11

Vaibhav Bajaj