You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python计算结束时间与开始时间的时间差?

Calculate Elapsed Time Between Two DateTime Strings in Python

Hey there! Calculating the elapsed time between your two datetime strings is super straightforward in Python. Here's a step-by-step breakdown of how to do it:

Step 1: Parse the datetime strings into datetime objects

First, we need to convert your raw string dates into Python's native datetime objects—since you can't subtract strings directly! We'll use the datetime.strptime() method, which lets us define a format string that matches your input structure.

Your datetime format is YYYYMMDD HH:MM:SS.sss, so the corresponding format code is %Y%m%d %H:%M:%S.%f.

Step 2: Compute the elapsed time

Once we have the two datetime objects, simply subtract the start time from the end time to get a timedelta object, which represents the difference between the two times.

Full Code Example

from datetime import datetime

# Your input datetime strings
start_date_time = "20200709 15:48:26.603"
end_date_time = "20200709 15:58:26.648"

# Define the format that matches your input
datetime_format = "%Y%m%d %H:%M:%S.%f"

# Parse the strings into datetime objects
start_dt = datetime.strptime(start_date_time, datetime_format)
end_dt = datetime.strptime(end_date_time, datetime_format)

# Calculate elapsed time
elapsed_time = end_dt - start_dt

# Print the formatted result
print(f"Elapsed Time: {elapsed_time}")
# Output: Elapsed Time: 0:10:00.045000

# If you need total seconds (including milliseconds) for calculations
print(f"Total Elapsed Seconds: {elapsed_time.total_seconds()}")
# Output: Total Elapsed Seconds: 600.045

Quick Notes

  • The timedelta object (elapsed_time) automatically formats the difference into hours:minutes:seconds.microseconds. In your case, it's 10 minutes and 45 milliseconds.
  • Use .total_seconds() if you need the total elapsed time as a floating-point number—handy for numerical calculations.

内容的提问来源于stack exchange,提问作者mahendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:32:48