Python: 将时间范围转换为秒数 (21:42-22:42)
使用 Python 代码可以将时间范围(例如'21:42-22:42')转换为秒数。以下是实现方法:
time_str = '21:42-22:42'
start, end = time_str.split('-')
start_hour, start_minute = map(int, start.split(':'))
end_hour, end_minute = map(int, end.split(':'))
start_seconds = start_hour * 3600 + start_minute * 60
end_seconds = end_hour * 3600 + end_minute * 60
time_duration = end_seconds - start_seconds
print(time_duration)
输出结果为:3600,即时间段的秒数。
代码解释:
- 将时间字符串
time_str拆分为开始时间start和结束时间end。 - 使用
map函数将开始时间和结束时间分别转换为小时和分钟的整数形式。 - 将小时和分钟转换为秒数,并计算开始时间和结束时间的秒数。
- 计算时间范围的秒数,即结束时间减去开始时间。
通过以上步骤,可以轻松地将时间范围转换为秒数。
原文地址: https://www.cveoy.top/t/topic/otqw 著作权归作者所有。请勿转载和采集!