如何使用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
timedeltaobject (elapsed_time) automatically formats the difference intohours: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

