簡體   English   中英

Python - 輸入用戶輸入的天數,然后顯示等效的年、月和日

[英]Python - Putting in user input of days and then displaying equivalent years, months and days

我正在努力為天數部分找到算法。 不過,我能夠減少幾年和幾個月的時間。 這是我的代碼

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()

首先,你把你的days ,做floor div 365,給你幾年。 然后,我們需要在剩下的日子,所以我們使用天modulus 365,讓余下的日子里,我們把那些做floor div 30,讓我們的幾個月。 然后我們用那些原來的剩余天數和modulus 30 來得到我們剩下的天modulus

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

這是divmod()一個很好的用途,它進行整數除法並為您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

如果沒有開始日期,您就無法真正做到這一點,因為月份會有所不同(尤其是在閏年)。 我建議將日期數學留給標准庫。 獲取開始日期的 datetime.datetime,使用“days”值構建 datetime.timedelta,將兩者相加得到結束日期,然后比較開始日期和結束日期的日、月和年。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM