Issue
I need a function returning a boolean indicating if midnight has just passed. I came up with this but I am not happy with the "form". Can anyone think of anything better? as in terms of efficiency/elegance?
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.today # see other comment below
time_ago = time_now() - timedelta(minutes=delta)
# next line with a dummy delta (zero) cuz "datetime.today - timedelta(days=1)" gives an error
today = time_now() - timedelta(days=0)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight, 10)
Solution
datetime.today - timedelta(days=1)
gives an error becausedatetime.today
is a function that needs to be called. This is why you must have felt the need to writetime_now()
with parentheses: it's calling the function, twice (with different results, because time has a tendency to pass).- Avoid
strftime
in favour ofdate()
, which returns the date part only (as adatetime.date
object). - Use
datetime.now()
instead ofdatetime.today()
so that subtracting atimedelta
can take the timezone (and hence daylight savings time changeovers) into account.
So then you get this:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.now()
time_ago = time_now - timedelta(minutes=delta)
return time_now.date() != time_ago.date()
Answered By - Thomas Answer Checked By - Candace Johnson (WPSolving Volunteer)