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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With