2025.10.21(更新日: 2025.10.21)
【Python】sum関数で秒の合計を出す
はじめに
sum関数で秒の合計を出す方法について見ていこう。
sum関数の基本
sum(iterable, start)
iterable・・・合計したいリストやタプルなど
start・・・初期値(デフォルトは整数の0)
サンプルコード
python/sum.py at 707dff44bd1bd680200cee77e4fcc6720da2c8fe · ki-hi-ro/python
sample_list = [1, 2, 3, 4, 5]
total_sum = sum(sample_list)
print(f"The sum of the list is: {total_sum}")
print("-----")
from datetime import timedelta
sample_list = [timedelta(days=2, hours=3), timedelta(hours=5, minutes=30), timedelta(days=1, minutes=45)]
total_sum = sum(sample_list, timedelta())
print(f"The sum of the list is: {total_sum}")
print("-----")
total_sum = sum(sample_list)
出力結果
The sum of the list is: 15
-----
The sum of the list is: 3 days, 9:15:00
-----
Traceback (most recent call last):
File "/Users/hiroki/Documents/python/sum.py", line 14, in <module>
total_sum = sum(sample_list)
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
数字のみのリスト
初期値がデフォルトの整数値0(sumの第二引数に何も指定しない場合)でも上手くいく。
sample_list = [1, 2, 3, 4, 5]
total_sum = sum(sample_list)
print(f"The sum of the list is: {total_sum}")
The sum of the list is: 15
日付と時間のリスト(sum関数の第二引数にtimedeltaを指定する)
初期値(sumの第二引数)にtimedelta()を指定すると上手くいく。
from datetime import timedelta
sample_list = [timedelta(days=2, hours=3), timedelta(hours=5, minutes=30), timedelta(days=1, minutes=45)]
total_sum = sum(sample_list, timedelta())
print(f"The sum of the list is: {total_sum}")
The sum of the list is: 3 days, 9:15:00
timedelta()の出力値は以下のようになる。
0:00:00
日付と時間のリスト(sum関数の第二引数に何も指定しない)
初期値がデフォルトの整数値0(sumの第二引数に何も指定しない)では上手くいかない。
total_sum = sum(sample_list)
Traceback (most recent call last):
File "/Users/hiroki/Documents/python/sum.py", line 14, in <module>
total_sum = sum(sample_list)
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
int (初期値の整数値0)+ datetime.timedeltaになってしまうから。
コメントを残す