我已经看过并试过一切。我是一名学生,这是一项家庭作业,但我无法弄清楚如何将时间添加到日期。我试图通过添加到达出发时间所需的小时和分钟来获取到达日期和时间,但它会不断增加天数和秒数。这就是我所拥有的:
#!/usr/bin/env python3
from datetime import datetime, timedelta
import locale
def get_departure_date():
while True:
date_str = input("Estimated date of departure (YYYY-MM-DD:)")
try:
departure_date = datetime.strptime(date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Try again.")
continue
now = datetime.now()
today = datetime(now.year, now.month, now.day)
if departure_date < today:
print("Departure date must be today or later. Try again")
continue
else:
return departure_date
def get_departure_time():
while True:
time_str = input("Estimated time of departure (HH:MM AM/PM:)")
try:
departure_time = datetime.strptime(time_str, "%I:%M %p")
except ValueError:
print("Invaild time format. Try again.")
continue
else:
return departure_time
def get_miles():
while True:
try:
miles = int(input("Enter miles:"))
except ValueError:
print("Invalid Integer. Please try again.")
continue
else:
return miles
def get_mph():
while True:
try:
mph = int(input("Enter miles per hour:"))
except ValueError:
print("Invalid Integer. Please try again.")
continue
else:
return mph
def main():
print("Arrival Time Estimator")
print()
while True:
departure_date = get_departure_date()
departure_time = get_departure_time()
miles = get_miles()
mph = get_mph()
hours = int(miles // mph)
minutes = int(miles - (60 * hours))
arrival_date = departure_date + timedelta(hours, minutes)
print("hours: ", hours)
print("minutes: ", minutes)
print (arrival_date)
print()
result = input("Continue? (y/n): ")
print()
if result.lower() != "y":
print("Bye!")
break
if __name__ == "__main__":
main()
答案 0 :(得分:0)
timedelta
构造函数在我看来并不是很直观。我发现使用命名参数最容易。
更改此行:
arrival_date = departure_date + timedelta(hours, minutes)
对此:
arrival_date = departure_date + timedelta(hours=hours, minutes=minutes)