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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With