用 fold 清理日光節約時間的資料
正如我們剛剛發現的,資料集中有一筆騎乘會受到日光節約時間轉換的影響而出錯。讓我們清理資料集,這樣才能得到正確的最短騎乘時間。我們可以利用「結束時間一定晚於開始時間」這個事實,來修正因為離開日光節約時間而被弄亂的騎乘時長。
由於 Python 在做運算時不會處理 tz.enfold(),我們必須把 datetime 物件轉成 UTC,這樣所有歧義就會被消除。
onebike_datetimes 已經載入且位於正確的時區。tz 和 timezone 已匯入。請使用 tz.UTC 作為時區。
本練習屬於課程
在 Python 處理日期與時間
練習說明
- 完成
if判斷式,只有在某趟行程的start晚於end時才為真。 - 當
start晚於end時,對end呼叫tz.enfold(),以表明它指的是日光節約時間變更之後的那一個。 - 在
if判斷式之後,將 start 與 end 轉換為 UTC,才能進行正確的比較。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
trip_durations = []
for trip in onebike_datetimes:
# When the start is later than the end, set the fold to be 1
if ____ > ____:
trip['end'] = tz.____(trip['end'])
# Convert to UTC
start = trip['start'].____
end = trip['end'].____
# Subtract the difference
trip_length_seconds = (end-start).total_seconds()
trip_durations.append(trip_length_seconds)
# Take the shortest trip duration
print("Shortest trip: " + str(min(trip_durations)))