-1

I am trying to compare two datetime.time but I keep getting the error:

"An exception of type TypeError occurred. Arguments: ("'<=' not supported between instances of 'datetime.datetime' and 'datetime.time'",)"

I've checked all of the types and they all seem to be of type datetime.time after I make a conversion (see print statements), but the terminal still screams the same error

print(appointment_start, type(appointment_start)) # 04:56:00 type <class 'datetime.time'>
print(appointment_end, type(appointment_end)) # <class 'datetime.time'>
print(time, type(time)) # <class 'datetime.datetime'>
formatted_time = time.time() # trying to convert to datetime.time
print(formatted_time, type(formatted_time)) # 09:00:00 <class 'datetime.time'>

if formatted_time >= appointment_start and time <= appointment_end:
            print('unavailable')
            return True

I've read SO answers that point out nothing is wrong with using >=. I even tried just using > but still the same problem arises.

uber
  • 4,163
  • 5
  • 26
  • 55

2 Answers2

1

Solution

Compare between the time part of datetime.datetime object and the datetime.time object. In other words, you need an apples-to-apples comparison.

import datetime

## Define datetime.datetime object
# dttm = datetime.datetime.now() # a datetime timestamp
dttm = datetime.datetime(2020, 11, 4, 22, 2, 7, 879029)
print(dttm)
print(repr(dttm))

# 2020-11-04 22:02:07.879029
# datetime.datetime(2020, 11, 4, 22, 2, 7, 879029)

## Define datetime.time object
tm = datetime.time(hour=10, minute=30, second=15, microsecond=0)
print(tm)
print(repr(tm))

# 10:30:15
# datetime.time(10, 30, 15)

## Compare
dttm.time() > tm

# True
CypherX
  • 7,019
  • 3
  • 25
  • 37
1

from a more general perspective: you can make an assertion:

import datetime

a, b = datetime.time(1,2,3), datetime.datetime(2020,4,5)
assert all(isinstance(i, datetime.time) for i in (a, b)), "all instances must be of type datetime.time!"
# AssertionError: all instances must be of type datetime.time!

a, b = datetime.time(1,2,3), datetime.time(4,5,6)
assert all(isinstance(i, datetime.time) for i in (a, b)), "all instances must be of type datetime.time!"
# (no error)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72