【问题标题】:How to make months not exceed 12如何使月份不超过12
【发布时间】:2021-01-11 02:26:18
【问题描述】:

我正在做一个小项目,代码将大致计算出它们 10 亿秒时的日期。我已经完成了,但我有一个问题。如果用户输入“5”作为月份或更高,则月份将超过 12。对于日期,如果用户输入“24”或更高,它将超过 31 天。我如何使它不会超过“12”几个月和“31”几天。唯一的问题是月份和日期,年份工作正常。谢谢!

运行代码时,您可以使用的示例是,“10”代表月份,“24”代表日,“2020”代表年。

代码:

month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

sum1 = day + 7
sum2 = month + 8
sum3 = year + 32

print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))

【问题讨论】:

标签: python


【解决方案1】:

虽然您可以使用 if 语句来做到这一点,但使用 datetime 内置库更简洁,它本机处理日期。

import datetime # imports it so it can be used

month = int(input("What Month Were You Born In: ")) #your code
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

born = datetime.datetime(year, month, day)#creates a datetime object which contains a date. Time defaults to midnight.

output = born + datetime.timedelta(seconds = 1_000_000_000)#defines and applies a difference of 1 billion seconds to the date

print(output.strftime("%m/%d/%Y")) #prints month/day/year

如果你确实想在没有日期时间的情况下这样做,你可以使用这个:

month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

sum1 = day + 7
sum2 = month + 8
sum3 = year + 32

if sum1 > 31: # checks if day is too high, and if it is, corrects that and addr 1 to the month to account for that.
    sum1 -= 31
    sum2 += 1
    
if sum2 > 12: #does the same thing for month
    sum2 -= 12
    sum3 += 1
    
print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))

请注意,此选项不如 datetime 选项精确,因为它没有考虑闰年或各种月份长度。

【讨论】:

  • 谢谢,我一定会试试这个,因为我对此比较熟悉。 (初学者)
  • 不客气。由于您是新来的,请不要忘记将最有助于解决问题的答案标记为已接受。
【解决方案2】:

您应该使用datetime 模块来正确处理将处理此类问题的日期。

timedelta 将允许您对 datetime 对象进行加、减等操作。

from datetime import datetime, timedelta

month = 6
day = 24
year = 1990

born = datetime(month=month, year=year, day=day)

billion = born + timedelta(seconds=1000000000)

print(billion)

#datetime.datetime(2022, 3, 2, 1, 46, 40)

print(billion.strftime('%d/%m/%Y'))

#'02/03/2022'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    相关资源
    最近更新 更多