Python-输入天的用户输入,然后显示等效的年,月和日

时间:2018-09-26 01:56:31

标签: python calculator

我正在努力寻找针对天数部分的算法。我可以把岁月和几个月都弄下来。这是我的代码

def main():

    # Prompt the user for an integer that represents a total number of days 
    user_days = int(input("Enter a total number of days: "))

    # constant variables for: years, months, days

    DAYS_IN_YEAR = 365
    DAYS_IN_MONTH = 30

    # Calculate the user's days into equivalent years
    years = (int(user_days // DAYS_IN_YEAR))

    # Calculate the user's days into equivalent months
    months = (int(user_days // DAYS_IN_MONTH))

    # Calculate the user's days into equivalent days
    # days = (int( user_days - DAYS_IN_MONTH ))
    # days = (int( ))

    # give user their results
    print(user_days, "days are equivalent to: ")

    # display the equivalent years
    print("Years: ", years)

    # display the equivalent months
    print("Months: ", months)

    # display the equivalent days
    print("Days: ", days)



main()

3 个答案:

答案 0 :(得分:1)

首先,您拿起days并在365年前完成floor div,这将给您带来很多年。然后我们需要剩余的天数,因此我们使用modulus的天数365来获取剩余的天数,我们将这些天数乘以floor div到30来求月数。那么我们将剩下的原始天数和modulus 30天作为剩余天数

days = int(input())
years = days // 365
years_r = days % 365
months = years_r // 30
days_r = years_r % 30
400
Years: 1, Months: 1, Days: 5
500
Years: 1, Months: 4, Days: 15

答案 1 :(得分:0)

这是divmod()的一个很好的用法,它可以进行整数除法,并为您提供商和余数:

user_days = 762

DAYS_IN_YEAR = 365
DAYS_IN_MONTH = 30

# Calculate number of years and remainder
years, rem = divmod(user_days, DAYS_IN_YEAR)

# Calculate number of months and remainder
months, days = divmod(rem, DAYS_IN_MONTH)

# Display results
print(user_days, "days are equivalent to: ")
print("Years: ", years)
print("Months: ", months)
print("Days: ", days)

# output:
# 762 days are equivalent to: 
# Years:  2
# Months:  1
# Days:  2

答案 2 :(得分:0)

没有开始日期就不能真正做到这一点,因为月份各不相同(尤其是leap年)。我建议将日期数学留给标准库。获取起始日期的datetime.datetime,使用您的“天”值构造一个datetime.timedelta,将二者相加以获得结束日期,然后比较开始日期和结束日期的日期,月份和年份。 / p>