I often tend to do various things that involve date arithmetic, and thought, “hey, what’s a simple quicky problem to get my feet wet in exploring python’s date/time support?
How about, “how many minutes from now until midnight?”
Here’s the documentation for builtin module “datetime”.
A quick glance shows several types: date, time, datetime and timedelta. The timedelta looked interesting, and examples suggest I can do math with these types, too.
My thinking is do something like “tomorrow – now”, converted to minutes.
Messing around in IDLE, I got tripped up trying to perform timedelta operations with mixed types, and surprise, you can’t do that:
>>> import datetime >>> date.today() + timedelta(1) datetime.date(2013, 1, 6) >>> datetime.now() datetime.datetime(2013, 1, 5, 20, 12, 25, 131993) >>> (date.today() + timedelta(1)) - datetime.now() Traceback (most recent call last): File "<pyshell#285>", line 1, in (date.today() + timedelta(1)) - datetime.now() TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' >>>
Ugh.
I gave up trying to use “date.today()”, and constructed ‘tomorrow’ as follows:
import datetime def how_many_minutes_until_midnight(): now = datetime.datetime.now() tomorrow = datetime.datetime(now.year, now.month, now.day) + \ datetime.timedelta(1) return abs(tomorrow - now).seconds / 60 print how_many_minutes_until_midnight()
POSTSCRIPT
The code written above was the original solution I came up with. But, it’s a bit ugly I think. Re-googling took me to these hits:
The latter whose comments revealed the use of time()
and datetime.combine
. So the above example can be improved further, I think. (Also note the different import statement.)
from datetime import * def how_many_minutes_until_midnight(): tomorrow = date.today() + timedelta(1) midnight = datetime.combine(tomorrow, time()) now = datetime.now() return (midnight - now).seconds / 60 print how_many_minutes_until_midnight()
Learnings / TODOs
I did note the timedelta also has “total_seconds()” in addition to “seconds”, the latter which is only the seconds portion of the the overall delta which could span multiple days. Since the nature of the calculation is within one day, either one is (mostly) equivalent for me:
return (midnight - now).seconds / 60
and
return (midnight - now).total_seconds() / 60
Testing these in IDLE showed that the latter returns a float, whereas the former is integer. But both get the job done.
References