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

如何将分钟转换为Timex格式(匹配Luis DateTimeRange规范)

Convert Total Minutes to ISO 8601 Duration Format (PTXHYM)

Got it, converting total minutes to that exact duration format (like PT7H30M for 450 minutes or PT30M for 30 minutes) is straightforward once you break down the logic. This format follows the ISO 8601 standard for durations, which is what Luis's DateTimeRange uses.

Core Logic

No matter what programming language you're working with, the steps are consistent:

  • Calculate full hours from total minutes: use floor division by 60
  • Get remaining minutes: use the modulus operator with 60
  • Build the duration string:
    • Start with PT (short for "Period Time")
    • Add the hour component (XH) if hours are greater than 0
    • Add the minute component (YM) if there are remaining minutes, or if there are 0 hours (to avoid empty/invalid strings)

Code Examples

Here are implementations in two common languages:

JavaScript

function minutesToISO8601(minutes) {
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  let duration = 'PT';
  
  if (hours > 0) {
    duration += `${hours}H`;
  }
  // Include minutes even if hours are 0 (handles cases like 0 minutes or 30 minutes)
  if (remainingMinutes > 0 || hours === 0) {
    duration += `${remainingMinutes}M`;
  }
  
  return duration;
}

// Test cases
console.log(minutesToISO8601(450)); // Output: PT7H30M
console.log(minutesToISO8601(30));  // Output: PT30M
console.log(minutesToISO8601(60));  // Output: PT1H
console.log(minutesToISO8601(0));   // Output: PT0M

Python

def minutes_to_iso8601(minutes):
    hours = minutes // 60
    remaining_minutes = minutes % 60
    duration_parts = []
    
    if hours > 0:
        duration_parts.append(f"{hours}H")
    # Ensure we always have a minute component if there are no hours
    if remaining_minutes > 0 or hours == 0:
        duration_parts.append(f"{remaining_minutes}M")
    
    return f"PT{''.join(duration_parts)}"

// Test cases
print(minutes_to_iso8601(450))  # PT7H30M
print(minutes_to_iso8601(30))   # PT30M
print(minutes_to_iso8601(60))   # PT1H
print(minutes_to_iso8601(0))    # PT0M

Quick Notes

  • This handles all non-negative minute values (if you need to support negative durations, just prepend a - before PT)
  • The output matches exactly the format you specified—no extra characters, just the standard ISO 8601 duration string

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:43:25