2013-10-07 3 views
2

시간을 찾기 위해 노력하고 있지만, 어떻게하는지 알고있는 유일한 방법은 아래에서 수행 한 작업을 사용하는 것입니다. 아래는 또한 내 출력이며, 당신이 볼 수 있듯이, 프로그램은 소수점 이하와 함께 초를 반환합니다.timedelta를 사용할 때 소수점 이하 자릿수가 많습니다.

CODE :

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

출력 :

9:46:04.352515 

내 질문이 있습니다 내가 그 "0.352515"을 제거 할 수있는 방법은? 가능하다면 초를 숨기고 싶습니다.

답변

5

를 포맷 timedelta 수동 :

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

데모 다음 .days 속성을 무시 않습니다

>>> 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' 

이 방법. 당신이 24 시간 이상으로 timedeltas이있는 경우 사용

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 

데모 :

>>> 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' 
관련 문제