Home > database >  Python: How to compare time in 24 Hrs format
Python: How to compare time in 24 Hrs format

Time:11-02

I am stuck with this tricky part with time manipulation:-

start_time = 22.00.00 -------------[10pm]

end_time = 05.00.00 ---------[5.0am]

current_time = 01.00.00 -----------[1am]

Here, I want to verify my current time is between start and end time.

This line of condition does not work here:-

if start_time < current_time < end_time:    
     DO THIS

How am I suppose to handle this ?

CodePudding user response:

Given that your time strings are in HH.MM.SS format, you can compare them directly as strings. However you need to take account of the fact that the period might span a 24-hour boundary, so that end_time < start_time. In that scenario you need to reverse the compare and invert the result.

start_time = "22.00.00"
end_time = "05.00.00"
current_time = "01.00.00"

if start_time < end_time and start_time < current_time < end_time or \
   end_time < start_time and not (end_time < current_time < start_time):
    # do this!
    pass

CodePudding user response:

If you want a straightforward universal solution you can use datetime.datetime.strptime like this

#!/usr/bin/env python
import datetime

start_time = "22.00.00"
end_time = "05.00.00"
current_time = "01.00.00"

start_dt = datetime.datetime.strptime(start_time, "%H.%M.%S")
end_dt = datetime.datetime.strptime(end_time, "%H.%M.%S")
current_dt = datetime.datetime.strptime(current_time, "%H.%M.%S")

if start_dt < current_dt < end_dt:
    print("wahoo!")
else:
    print("wrong")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

However, there is actually a less readable yet faster way to do it which avoids actually analyzing the date, which is you to make a number from the strings like this.

#!/usr/bin/env python
start_time = "22.00.00"
end_time = "05.00.00"
current_time = "01.00.00"

if int(start_time.replace(".","")) < int(current_time.replace(".","")) < int(end_time.replace(".","")):
    print("wahoo!")
else:
    print("wrong")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

  • Related