在Python中,将秒数转换为时分秒的方法有多种,以下是几种常见的方法:
方法一:使用 `divmod()` 函数
def seconds_to_hms(seconds_num):
h, m = divmod(seconds_num, 60)
m, s = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
方法二:使用 `datetime` 模块
from datetime import datetime, timedelta
def seconds_to_hms_datetime(seconds_num):
d = datetime.datetime(1, 1, 1) + timedelta(seconds=seconds_num)
return d.strftime("%H:%M:%S")
方法三:使用 `strftime()` 和 `gmtime()` 函数
from time import strftime, gmtime
def seconds_to_hms_strftime(seconds_num):
return strftime("%H:%M:%S", gmtime(seconds_num))
方法四:使用数学计算
def seconds_to_hms_math(seconds_num):
SecToConvert = seconds_num
RemainingSec = SecToConvert % (24 * 3600)
HoursGet = RemainingSec // 3600
RemainingSec %= 3600
MinutesGet = RemainingSec // 60
RemainingSec %= 60
return f"{HoursGet:02d}:{MinutesGet:02d}:{RemainingSec:02d}"
方法五:使用 `pandas` 和 `timedelta`
import pandas as pd
from datetime import timedelta
def seconds_to_hms_pandas(seconds_num):
df = pd.DataFrame({'时长': [timedelta(seconds=seconds_num)]})
return df['时长'].map(lambda x: x.total_seconds()).map(lambda x: f"{int(x):02d}:{int((x % 3600):02d}):{int((x % 60):02d}")