Convert date and time to hours?

I have a datetime stamp (e.g. time(6,30) ) that will be returned at 06:30:00. I was wondering how I could convert this to 6.5 hours.

Yours faithfully

+5
source share
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 and multiseconds, 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 suffix 'hrs' :

 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 
+2
source

Assuming you mean 6.5 hours elapsed time, this will be timedelta . The time object is for the time of day, for example, at a 24-hour hour. These are different concepts and should not be mixed.

You also should not think of the time of day as "time elapsed from midnight," as some days include daylight saving time, which can increase or decrease this value. For example, for most places in the United States, 2017-11-05, the time you gave 06:30:00 will be 7.5 hours past midnight, since there is an hour between 1 and 2 repetitions to go back.

So the answer to your question is no.

+1
source

Source: https://habr.com/ru/post/1270086/


All Articles