E J
E J

Reputation: 81

How to add minutes to a datetime range comparison?

How can I alter the below to account for minutes as well as our in datetime range?

For example the below works fine.

from datetime import datetime

if (datetime.now().hour>=14) and (datetime.now().hour<=16):
         print ('afternoon' )

else:
        print ('not afternoon')

If the time now is past 14:30 but before 16:30 print afternoon.

Upvotes: 0

Views: 629

Answers (2)

Elidor00
Elidor00

Reputation: 1622

from datetime import datetime, time

def checkTime(t):
    if time(14, 30) <= t <= time(16, 30):
        print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is afternoon" )
    else:
        print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is not afternoon" )

checkTime(time(15,15)) # time: 15h 15m is afternoon
checkTime(time(14,30)) # time: 14h 30m is afternoon
checkTime(time(15,31)) # time: 15h 31m is afternoon
checkTime(time(14,29)) # time: 14h 29m is not afternoon
checkTime(time(16,31)) # time: 16h 31m is not afternoon
checkTime(time(18,10)) # time: 18h 10m is not afternoon

Upvotes: -1

Chris Doyle
Chris Doyle

Reputation: 11968

You can use time from datetime to make timeobjects. So you can create a time object for your start time and a time object for your end time. then you can just extract the timeobject from you datetime and compare it with a simple between expression. I have used timedelta, to just manipulate the current date time to show this working.

from datetime import datetime, timedelta, time

datetimes = []
datetimes.append(datetime.now())
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
start_time = time(14, 30)
end_time = time(16, 30)
for current in datetimes:
    print(f"Time: {current.hour:02}:{current.minute:02}")
    if start_time <= current.time() <= end_time:
        print("afternoon")
    else:
        print("not afternoon")

OUTPUT

Time: 11:22
not afternoon
Time: 14:42
afternoon
Time: 18:02
not afternoon

Upvotes: 3

Related Questions