Home > Mobile >  Comparing times in Python
Comparing times in Python

Time:11-17

I've no idea what I'm doing wrong in the following line of code and it's driving me nuts! As you'll probably know from the code, I only want the if block to run if it's before 5.15pm.

if time(datetime.now().hour,datetime.now().minute) < time(17, 15):

I've imported date and datetime so that's not the issue (it's TypeError error - see below error message I'm getting)

Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: _run_module_as_main) 'module' object is not callable

Can someone advise on what I'm doing wrong

CodePudding user response:

a bit shorter:

from datetime import datetime, time

datetime.now().time() < time(20,10)  # False

CodePudding user response:

You probably want to from datetime import time:

from datetime import datetime, time

now = datetime.now()

if time(now.hour, now.minute) < time(20, 15):
    print("Hello")

Prints (now):

Hello
  • Related