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

Python添加时分至日期计算到达时间的问题求助

Fixing Unwanted Days/Seconds in Your Datetime Calculation

Hey Lisa, let's work through this datetime issue you're facing—those unexpected days and seconds popping up are definitely a tricky roadblock for your homework!

First, let's break down the core problem: when you add travel hours/minutes to your departure time, timedelta is probably picking up extra parameters you don't intend, or your input handling is accidentally feeding it incorrect values. Let's walk through solutions and common pitfalls to avoid.

Common Mistakes That Cause Extra Days/Seconds

  • Accidentally passing seconds instead of minutes: If you write timedelta(hours=2, seconds=30) instead of timedelta(hours=2, minutes=30), you're adding 2 hours and 30 seconds—not 2h30m. Over time, those seconds can accumulate into minutes/hours, or if you're using large numbers, even days.
  • Manual time calculation instead of using timedelta: If you try to add minutes directly to the departure time's minute attribute (e.g., departure.minute + travel_minutes), you'll run into issues when minutes exceed 60. This can lead to incorrect hour increments, and if hours exceed 24, you'll get wrong day counts because you're not letting Python handle the time math automatically.
  • Incomplete departure datetime: If you only parse the departure date (not time), Python defaults to 00:00:00. Adding a long travel duration (like 25 hours) will correctly add a day, but if you didn't expect that, it might feel like an error.

Corrected Code Example

Here's a refined version of your script that avoids those pitfalls, with clear input handling and proper timedelta usage:

#!/usr/bin/env python3
from datetime import datetime, timedelta
import locale

def get_departure_datetime():
    while True:
        try:
            # Get full date + time input to avoid default midnight
            dt_input = input("Estimated date of departure (YYYY-MM-DD HH:MM): ")
            departure_dt = datetime.strptime(dt_input, "%Y-%m-%d %H:%M")
            return departure_dt
        except ValueError:
            print("Oops, that format isn't right! Please use YYYY-MM-DD HH:MM (e.g., 2024-05-20 14:30)")

def get_travel_duration():
    while True:
        try:
            travel_hours = int(input("Travel duration (hours): "))
            travel_minutes = int(input("Travel duration (minutes): "))
            # Only pass hours and minutes to timedelta—no extra days/seconds
            return timedelta(hours=travel_hours, minutes=travel_minutes)
        except ValueError:
            print("Please enter whole numbers for hours and minutes!")

def calculate_arrival():
    departure = get_departure_datetime()
    travel_time = get_travel_duration()
    arrival_dt = departure + travel_time
    
    # Format output to hide seconds (since we don't need them)
    print(f"Estimated arrival: {arrival_dt.strftime('%Y-%m-%d %H:%M')}")

if __name__ == "__main__":
    calculate_arrival()

Key Fixes & Tips

  1. Full Datetime Parsing: By asking for both date and time, you avoid unexpected midnight defaults that can lead to unintended day changes.
  2. Targeted timedelta Usage: We only pass hours and minutes to timedelta, so there's no chance of accidental seconds or days being added. Python handles all the time math (like 23:40 + 50 minutes = 00:30 next day) automatically.
  3. Formatted Output: Using strftime('%Y-%m-%d %H:%M') ensures we don't display unnecessary seconds (which datetime objects default to 0 if not specified).

How to Debug Your Original Code

If you want to fix your existing script instead of starting fresh:

  • Print intermediate values: Add print(departure) and print(travel_duration) to check if those objects match what you expect.
  • Double-check timedelta arguments: Make sure you're not passing days or seconds unless you explicitly need them.
  • Verify input parsing: Ensure your departure date/time is being converted to a full datetime object, not just a date object.

That should clear up those unwanted days and seconds! Let me know if you hit any other snags with your code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:31:44