Python添加时分至日期计算到达时间的问题求助
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 oftimedelta(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
- Full Datetime Parsing: By asking for both date and time, you avoid unexpected midnight defaults that can lead to unintended day changes.
- Targeted
timedeltaUsage: We only passhoursandminutestotimedelta, 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. - Formatted Output: Using
strftime('%Y-%m-%d %H:%M')ensures we don't display unnecessary seconds (whichdatetimeobjects 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)andprint(travel_duration)to check if those objects match what you expect. - Double-check
timedeltaarguments: Make sure you're not passingdaysorsecondsunless you explicitly need them. - Verify input parsing: Ensure your departure date/time is being converted to a full
datetimeobject, not just adateobject.
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

