python分秒加减法
时间: 2024-01-06 21:25:35 浏览: 73
以下是使用strftime()和gmtime()函数将秒转换为时分秒的示例代码:
```python
from time import gmtime, strftime
def seconds_to_hms(seconds):
time_struct = gmtime(seconds)
hms = strftime("%H:%M:%S", time_struct)
return hms
seconds = 3666
hms = seconds_to_hms(seconds)
print("Time in HH:MM:SS format:", hms) # 输出:Time in HH:MM:SS format: 01:01:06
```
以下是使用divmod()函数进行分秒加减法的示例代码:
```python
def add_seconds(time, seconds):
hours, minutes, old_seconds = map(int, time.split(':'))
total_seconds = hours * 3600 + minutes * 60 + old_seconds
new_total_seconds = total_seconds + seconds
new_hours, remaining_seconds = divmod(new_total_seconds, 3600)
new_minutes, new_seconds = divmod(remaining_seconds, 60)
new_time = f"{new_hours:02d}:{new_minutes:02d}:{new_seconds:02d}"
return new_time
time = "01:01:06"
seconds_to_add = 120
new_time = add_seconds(time, seconds_to_add)
print("New time after adding seconds:", new_time) # 输出:New time after adding seconds: 01:03:06
```
阅读全文