Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many decimal places when using timedelta

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.

like image 846
l00kitsjake Avatar asked Oct 18 '25 13:10

l00kitsjake


2 Answers

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'
like image 124
Martijn Pieters Avatar answered Oct 21 '25 03:10

Martijn Pieters


Very simple solution

from datetime import timedelta

def format_seconds(seconds: float, decimal_places: int = 2):
    return str(timedelta(seconds=seconds))[: -6 + decimal_places]
>>> format_seconds(123.1234123123) 
'0:02:03.12'
>>> format_seconds(123.0999999999)  
'0:02:03.10'
>>> format_seconds(123.0999999999, decimal_places=4) 
'0:02:03.1000'
>>> format_seconds(123.1234124, decimal_places=4)    
'0:02:03.1234'
like image 36
Angel Avatar answered Oct 21 '25 03:10

Angel