向用户显示到达时间和日期

时间:2019-04-13 16:17:52

标签: python

如何添加时间增量,以便可以将增量值添加到DateTime值并进行打印?例如,估计的旅行时间小时:6 分钟:15.0 预计抵达日期:2018-11-30 预计到达时间:05:30 AM

但是我的程序只是显示以下内容: 预计旅行时间 时间:3 分钟:4`

from datetime import datetime,timedelta
import locale

mph = 0
miles = 0
def get_departure_time():
    while True:
        date_str = input("Estimated time of departure (HH:MM AM/PM):  ")
        try:
            depart_time = datetime.strptime(date_str, "%H:%M %p")
        except ValueError:
            print("Invalid date format. Try again.")
            continue
        return depart_time


def get_departure_date():
    while True:
        date_str = input("Estimated date of departure (YYYY-MM-DD): ")
        try:
            depart_date = datetime.strptime(date_str, "%Y-%m-%d")
        except ValueError:
            print("Invalid date format. Try again. ")
            continue
        return depart_date

def distance():
    while True:
        miles = input("Enter miles to be travelled: ")
        try:
            miles = int(miles)
            if miles <= 0:
                print("Enter a Number Greater than 0.\n")
            else:
                return miles
        except ValueError:
            print("Format Error . Please Try again\n")
            continue

def speed():
    while True:
        speed = input("Enter miles per hour: ")
        try:
            mph = int(speed)
            if mph <= 0:
                print("Enter a Number Greater than 0.\n")
            else:
                return mph
        except ValueError:
            print("Format Error . Please Try again\n")
            continue
        pass

def travel_calculations(miles,mph):
    hours = int(miles/mph)
    minutes = int(((miles/mph)-hours)*60)
    time_travelled = timedelta(hours=hours, minutes=minutes)



    print("\n\nEstimated travel time")
    print("Hours: ", hours)
    print("Minutes: ", minutes)


def main():
    print("Arrival Time Estimator\n")
    depart_time = get_departure_time()
    depart_date = get_departure_date()

    miles = distance()
    mph = speed()
    travel_calculations(miles,mph)
    return


if __name__ == "__main__":
    main()

`

1 个答案:

答案 0 :(得分:0)

depart_timedepart_date合并到datetime函数中的一个main()对象,并将其提供给travel_calculations()

def main():
    ...
    departure = depart_date.replace(hour=depart_time.hour, minute=depart_time.minute)
    ...
    travel_calculations(miles, mph, departure)

请注意,最好一次获取时间和日期并创建一个datetime对象,而不是随后再将它们添加在一起。

然后,在travel_calculations()中,将您的timedelta添加到datetime对象

def travel_calculations(miles, mph, departure):
    ...
    eta = departure + time_travelled

然后,您可以在eta变量中获得估计的到达时间。