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)
datetime.today - timedelta(days=1)gives an error becausedatetime.todayis 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).strftimein favour ofdate(), which returns the date part only (as adatetime.dateobject).datetime.now()instead ofdatetime.today()so that subtracting atimedeltacan take the timezone (and hence daylight savings time changeovers) into account.So then you get this: