開始使用免費開始

將成對的 datetime 轉換為持續時間

在處理時間戳記時,我們常常想知道事件之間經過了多少時間。所幸可以使用 datetime 的運算,請 Python 自動處理,這樣就不用擔心跨日、跨月或跨年的邊界問題。現在就來計算每趟旅程中腳踏車離開停車座的秒數。

延續先前的程式練習,腳踏車旅程資料已載入為清單 onebike_datetimes。清單中的每個元素都包含兩個 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)
編輯並執行程式碼