我有这个方法,它接收秒(作为整数)并返回一个包含年、日、小时、分钟和秒的字符串。
当任何值(年、日、小时、分钟或秒)= 1 时,它不会被格式化。我尝试解析为字符串,但仍然不起作用。有人知道发生了什么事吗?
def seconds_to_text(sec):
m = sec//60
h = m//60
d = h//24
years = d//365
days = d - years*365
hours = h - d*24
minutes = m - h*60
seconds = sec % 60
text = ''
if years != 0:
text += f'{years}' + ' years, ' if years > 1 else ' year, '
if days != 0:
text += f'{days}' + ' days, ' if days > 1 else ' day,'
if hours != 0:
text += f'{hours}' + ' hours, ' if hours > 1 else ' hour, '
if minutes !=0:
text += f'{minutes}' + ' minutes ' if minutes > 1 else ' minute '
if seconds != 0:
text += f'and {seconds}' + ' seconds' if seconds > 1 else ' second'
return text
print(seconds_to_text(1501011301))
// Output: 47 years, 217 days, 19 hours, 35 minutes second
我尝试过使用 print(f'and {seconds}') ,输出很好,它显示 1。我也尝试过使用 str(seconds) ,但它也不起作用。 谢谢你的帮助
已解决:
抱歉,将 if 语句放在括号之间出现了问题
text += f'and {秒}' + ('秒'如果秒> 1,否则'秒')
不仅仅是秒。试试
print(seconds_to_text(61))
问题在于这部分:
text += f'and {seconds}' + ' seconds' if seconds > 1 else ' second'
... 如果秒 > 1,则返回
f'and {seconds}' + ' seconds'
,否则返回 ' second'
。