开始使用免费开始使用

将成对的 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)
编辑并运行代码