28

I have a Python datetime, d, and I want to get the number of hours since midnight as a floating point number. The best I've come up with is:

h = ((((d.hour * 60) + d.minute) * 60) + d.second) / (60.0 * 60)

Which gives 4.5 for 4:30am, 18.75 for 6:45pm, etc. Is there a better way?

Chris Nelson
  • 3,519
  • 7
  • 40
  • 51

2 Answers2

42
h = d.hour + d.minute / 60. + d.second / 3600.

has less brackets…

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 1
    I am surprised that datetime objects do not have a method like ".get_hours" that does this!! – Tommy Oct 07 '15 at 14:02
  • 1
    @ChrisNelson: beware, floating point arithmetic differs from the usual math i.e., even if the formulae look equivalent; they may produce different results (whether it is the case here or whether it matters even if it is depends on your application) e.g., [floating point issues in `.total_seconds()` method](http://bugs.python.org/issue8644) – jfs Oct 07 '15 at 16:34
5
h = (d - d.replace(hour=0,minute=0,second=0)).seconds / 3600.

... has less division and/or multiplication

MattH
  • 37,273
  • 11
  • 82
  • 84
  • @eumiro: Nope, I was just referring to typed code as I'd lost out on bracket frugality! – MattH Dec 01 '11 at 15:16
  • @ovgolovin: The OP isn't counting microseconds, so if not in the replace method they'll be substracted out of the result. Actually microseconds are stored separately on the timedelta object, so I'm just not regarding them as the OP hasn't. – MattH Dec 01 '11 at 15:18
  • I know division and multiplication are expensive in hardware but I don't trust date math to be efficient. I suppose replace() should be fast but computing a timedelta worries me. Perhaps that's premature optimization. – Chris Nelson Dec 02 '11 at 15:41