始める無料で始める

datetime のペアを継続時間に変換する

タイムスタンプを扱うとき、イベント間でどれだけ時間が経過したかを知りたいことがよくあります。幸い、datetime の演算を使えば、日・月・年の境界を気にせずに、Python に重い処理を任せられます。各トリップで自転車がドックから外れていた秒数を計算してみましょう。

以前のコーディング演習から続けて、バイクのトリップデータはリスト onebike_datetimes として読み込まれています。リストの各要素は2つの datetime オブジェクトからなり、それぞれトリップの開始時刻と終了時刻を表します。

この演習はコースの一部です

Pythonで扱う日付と時刻

コースを見る

演習の手順

  • ループ内で次を行います。
    • startend の要素に対して演算を行い、トリップの長さを求める
    • 結果を 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)
コードを編集して実行