Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime into number of hours?

I have a datetime stamp (e.g. time(6,30)) which would return 06:30:00. I was wondering how I could then convert this into 6.5 hrs.

Kind regards

like image 1000
JaneDoez Avatar asked Jul 21 '17 22:07

JaneDoez


2 Answers

You can simply use:

import datetime

the_time = datetime.time(6,30)
value = the_time.hour + the_time.minute/60.0

If you want to take seconds an multiseconds into account as well, you can use:

import datetime

the_time = datetime.time(6,30)
value = the_time.hour + the_time.minute/60.0 + \
            the_time.second/3600.0 + the_time.microsecond/3600000000.0

Both here generate:

>>> the_time.hour + the_time.minute/60.0
6.5
>>> the_time.hour + the_time.minute/60.0 + \
...             the_time.second/3600.0 + the_time.microsecond/3600000000.0
6.5

Or if you want to print it with the 'hrs' suffix:

import datetime

the_time = datetime.time(6,30)
print('{} hrs'.format(the_time.hour + the_time.minute/60.0))

This will print:

>>> print('{} hrs'.format(the_time.hour + the_time.minute/60.0))
6.5 hrs
like image 174
Willem Van Onsem Avatar answered Oct 07 '22 12:10

Willem Van Onsem


Assuming that you mean 6.5 hours of elapsed time, that would be a timedelta. The time object is for time-of-day, as on a 24-hour clock. These are different concepts, and shouldn't be mixed.

You should also not think of time-of-day as "time elapsed since midnight", as some days include daylight saving time transitions, which can increase or decrease this value. For example, for most locations of the United States, on 2017-11-05 the time you gave of 06:30:00 will have 7.5 hours elapsed since midnight, as the hour between 1 and 2 repeats for the fall-back transition.

So the answer to your question is - don't.

like image 44
Matt Johnson-Pint Avatar answered Oct 07 '22 12:10

Matt Johnson-Pint