from datetime import timedelta
def convert_delta(dlt: timedelta) -> str:
minutes, seconds = divmod(int(dlt.total_seconds()), 60)
return f"{minutes}:{seconds:02}"
# this is your time from your code
dlt = timedelta(minutes=1, seconds=3, milliseconds=681.325)
print(convert_delta(dlt))
# Convert timedelta to string:
td_str = str(timedelta(seconds=end-start))
# Starting index of slice is the position of the first number in td_str that isn't '0':
starting_numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}
for character_index, character in enumerate(td_str):
if character in starting_numbers:
start_slice_index = character_index
break
# End of slice is always '.':
end_slice_index = td_str.index(".")
# Make sure that time still displays as '0:xx' when time goes below one minute:
if end_slice_index - start_slice_index <= 3:
start_slice_index = end_slice_index - 4
# Print slice of td_str:
print(f'{td_str[start_slice_index:end_slice_index]}')
3条答案
按热度按时间sulc1iza1#
如果只依赖
timedelta
对象的默认字符串表示,则会得到该格式。相反,您必须指定自己的格式:这样你就得到了这个输出:
k7fdbhmy2#
根据wkl的回答,你可以用
int(input())
输入分、秒,用float(input())
输入毫秒。nwsw7zdq3#
简单地打印字符串的一个切片怎么样?例如:
此解决方案的优点是,如果时间超过一个小时,打印的时间仍然正确显示。