开始使用免费开始使用

使用 fold 清洗夏令时数据

正如我们刚刚发现的,数据集中有一次骑行因夏令时切换而出错。现在来清洗数据,这样我们才能得到正确的最短骑行时长。我们可以利用"骑行结束晚于开始"这一事实,来修正因退出夏令时导致的时长错误。

由于 Python 在进行算术运算时不会处理 tz.enfold(),我们必须将 datetime 对象转换为 UTC,在那里歧义已经被消除。

onebike_datetimes 已加载并处于正确的时区。tztimezone 已经导入。请使用 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)))
编辑并运行代码