Skip to content
Advertisement

How do I determine if current time is within a specified range using Python’s datetime module?

What would be the best way to see if the current time lies between say 10:30 AM and 4:30 PM.

I could think of the following, not sure how correct:

JavaScript

Please let me know if this the correct approach, can something better be written?

Advertisement

Answer

My original answer focused very specifically on the question as posed and didn’t accommodate time ranges that span midnight. As this is still the accepted answer 6 years later, I’ve incorporated @rouble’s answer below that expanded on mine to support midnight.

JavaScript

I still stick to my original comment below that most applications of this logic would probably be better suited with datetime objects where crossing midnight is reflected as a date change anyway.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement