How can I get hours from a Python datetime?

Question:

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?

Asked By: Chris Nelson

||

Answers:

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

has less brackets…

Answered By: eumiro
h = (d - d.replace(hour=0,minute=0,second=0)).seconds / 3600.

… has less division and/or multiplication

Answered By: MattH
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.