3
votes

The general convention for a generic range (x,y) is that x is inclusive and y is exclusive.

For Python datetime.time type, datetime.time.max is time(23, 59, 59, 999999), so it doesn't seem to allow to use the conventional range check on the upper end. For example, if I want to check a time range between 10 am and midnight, I might want a range like this: (time(10), time(24)). But time(24) is not valid, even as a sentinel value.

On the other hand, we can't make x exclusive and y inclusive, because then we lose time(0) as a value.

Should range checks on time be inclusive? Something about it doesn't seem right to me, but I can't articulate it.

1
If you use datetime instead of time you can use midnight of the following day as your upper bound. But if you don't actually care about the date you would need a dummy value there (1970-1-1 and 1970-1-2, maybe?) which is a bit of a hack.0x5453
I notice that the error message for datetime.time(24) is ValueError: hour must be in 0..23. Since 0 and 23 are both permissible values, this may indicate the author's preference about incluvisity of end points in the context of times.Kevin
I suppose the issue does not really come up in practice, because you would not generally check a time in a finite range of time values. You would check it by using inequalities, so choosing < or <= as you want. For same reason we don't check floats in a range of floats.wim
Thanks all. I appreciate all the thoughts expressed here. It seems that the practical approach to time ranges depends on the context of the problem.jacob

1 Answers

0
votes

Use 0 for midnight

Instead of:

(time(10), time(24))

Use:

# From midnight (0:00) to 10am (10:00)
(time(0), time(10))