![](/img/trans.png)
[英]How to convert A "hours and minutes and seconds" string to HH:MM:SS format?
[英]How convert seconds in minutes and seconds (mm:ss)
是否可以使用这种格式“mm:ss”将秒转换为分和秒? 我尝试使用datetime.timedelta(seconds=seconds)
但它返回 hh:mm:ss 格式。
提前致谢!
您可以为此使用divmod
。
hours, remainder = divmod(someSecondsValue, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"{minutes:02}:{seconds:02}")
您可以通过除以 60 来获得分钟数,通过计算提醒除以 60 来获得秒数。
total_seconds = 10000
minutes = int(total_seconds / 60)
seconds = total_seconds % 60
print(f"{minutes}:{seconds}")
您还可以制作一个小的自定义时间 class 并使用__format__
来控制您希望如何打印出来:
class MyTime:
def __init__(self, seconds: int):
self.total_seconds = seconds
def __format__(self, format_spec: str) -> str:
if format_spec == 'm':
minutes = self.total_seconds // 60
seconds = self.total_seconds % 60
return f'{minutes:02}:{seconds:02}'
if format_spec == 'h':
hours = self.total_seconds // 3600
minutes = (self.total_seconds - hours * 3600) // 60
seconds = self.total_seconds % 60
return f'{hours:02}:{minutes:02}:{seconds:02}'
# ...other formats...
return str(self.total_seconds)
x = MyTime(3674)
print(f'Seconds: {x}') # 3674
print(f'Minutes & seconds: {x:m}') # 61:14
print(f'Hours & minutes & seconds: {x:h}') # 01:01:14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.