如何获取秒/分/小时级时间差?仅时间字符串的差值计算
Got it, let's walk through how to calculate the time difference between two 12-hour format times like 02:00 PM and 10:00 PM—no dates needed, just pure time math. Here's the breakdown:
No matter which programming language you use, the core steps are always these three:
- Convert the format: Turn the 12-hour string (with AM/PM) into a time format the program can calculate with (like 24-hour numerical values or a dedicated time object)
- Calculate the difference: Subtract the converted time values to get a time interval
- Convert units: Turn the interval into seconds, minutes, or hours based on what you need
Python's datetime module handles the AM/PM conversion automatically, so you don't have to mess with manual logic. Let's jump into code:
from datetime import datetime, timedelta # Your two time strings time_a = "02:00 PM" time_b = "10:00 PM" # Parse the strings: %I = 12-hour format hour, %M = minutes, %p = matches AM/PM parsed_time_a = datetime.strptime(time_a, "%I:%M %p") parsed_time_b = datetime.strptime(time_b, "%I:%M %p") # Calculate the time difference time_delta = parsed_time_b - parsed_time_a # Convert to different units total_seconds = time_delta.total_seconds() total_minutes = total_seconds / 60 total_hours = total_minutes / 60 # Output results print(f"Time difference (seconds): {int(total_seconds)}") # 28800 seconds print(f"Time difference (minutes): {int(total_minutes)}") # 480 minutes print(f"Time difference (hours): {total_hours}") # 8.0 hours
If your times might cross midnight (e.g., 10:00 PM to 02:00 AM the next day), the code above will return a negative difference. Fix this with a quick check:
if time_delta.days < 0: time_delta += timedelta(days=1) # Now converting units will give the correct cross-day difference (e.g., 4 hours for 10PM to 2AM)
- JavaScript: Use the
Dateobject by appending a default date to your time string (e.g.,new Date("2020-01-01 " + timeStr)), then calculate the difference between the two timestamps and convert units - Java: Use
SimpleDateFormatto parse strings intoDateobjects, get their timestamps, subtract, then convert units - PHP: Use
strtotime()to turn time strings into timestamps, subtract, then convert units
The core idea is always the same: convert the human-readable string into a computable time value, do the subtraction, then adjust to your desired unit!
内容的提问来源于stack exchange,提问作者Krishna

