datetime のペアを継続時間に変換する
タイムスタンプを扱うとき、イベント間でどれだけ時間が経過したかを知りたいことがよくあります。幸い、datetime の演算を使えば、日・月・年の境界を気にせずに、Python に重い処理を任せられます。各トリップで自転車がドックから外れていた秒数を計算してみましょう。
以前のコーディング演習から続けて、バイクのトリップデータはリスト onebike_datetimes として読み込まれています。リストの各要素は2つの datetime オブジェクトからなり、それぞれトリップの開始時刻と終了時刻を表します。
この演習はコースの一部です
Pythonで扱う日付と時刻
演習の手順
- ループ内で次を行います。
startとendの要素に対して演算を行い、トリップの長さを求める- 結果を
trip_durationに保存する trip_durationからtrip_length_secondsを計算する
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Initialize a list for all the trip durations
onebike_durations = []
for trip in onebike_datetimes:
# Create a timedelta object corresponding to the length of the trip
trip_duration = ____[____] - ____[____]
# Get the total elapsed seconds in trip_duration
trip_length_seconds = trip_duration.____()
# Append the results to our list
onebike_durations.append(trip_length_seconds)