Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get hours from a Python datetime?

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?

like image 606
Chris Nelson Avatar asked Dec 01 '11 14:12

Chris Nelson


People also ask

How do you get just the time from a datetime in Python?

We can get a datetime object using the strptime() method by passing the string which contains date and time and get a datetime object. We can then get the hour and minute from the datetime object by its . hour and . minute attributes.


1 Answers

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

has less brackets…

like image 187
eumiro Avatar answered Sep 22 '22 10:09

eumiro