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

如何获取秒/分/小时级时间差?仅时间字符串的差值计算

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 为例)

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
Handle cross-day scenarios (optional)

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)
Quick overview for other languages
  • JavaScript: Use the Date object 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 SimpleDateFormat to parse strings into Date objects, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:01