Pergunta

I am trying to find the time in hour and minutes however, the only way I know how to do it is by using what I have done below. Below is also my output and as you can see, it the program returns seconds along with decimals after.

CODE:

def commercial_time (distance, speed_of_commercial):
    time = distance / speed_of_commercial
    seconds = time * 3600
    real = (datetime.timedelta(seconds = seconds))
    return real

OUTPUT:

9:46:04.352515

My question is, is there a way I can get rid of that ".352515"? I would also like to hide the seconds as well if that is possible.

Foi útil?

Solução

Format the timedelta manually:

def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}'.format(hours, minutes)

Demo:

>>> from datetime import timedelta
>>> def custom_format(td):
...     minutes, seconds = divmod(td.seconds, 60)
...     hours, minutes = divmod(minutes, 60)
...     return '{:d}:{:02d}'.format(hours, minutes)
... 
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'

This method does ignore the .days attribute. If you have timedeltas with more than 24 hours, use:

def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    formatted = '{:d}:{:02d}'.format(hours, minutes)
    if td.days:
        formatted = '{} day{} {}'.format(
            td.days, 's' if td.days > 1 else '', formatted)
    return formatted

Demo:

>>> custom_format(timedelta(days=42, hours=9, minutes=46, seconds=4, microseconds=352515))
'42 days 9:46'
>>> custom_format(timedelta(days=1, hours=9, minutes=46, seconds=4, microseconds=352515))
'1 day 9:46'
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'

Outras dicas

Convert the timedifference to a string with str(), then separate on either side of the decimal place with .split('.'). Then keep the first portion before the decimal place with [0]:

Your example with the only difference on the last line:

import time
import datetime

def commercial_time (distance, speed_of_commercial):
    time = distance / speed_of_commercial
    seconds = time * 3600
    real = (datetime.timedelta(seconds = seconds))
    return str(real).split('.')[0]

then:

print( commercial_time( 10 , 1.025 ) )

generates:

9:45:21
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top