我试图找出有人会在10亿秒之前变老的时候。用户在他们出生时输入。然后将这些值转换为秒,然后再添加10亿秒并转换回日期。但是,当我输入某些日期时,python似乎搞得一团糟。这样的例子是1993/11/05 00:00:00,其中python说用户将在第0个月转向。 注意我不能使用if / else或datetime。
继承我的代码:
YEARSEC=(12*30*24*3600)
MONTHSEC=(3600*24*30)
DAYSEC=(24*3600)
HOURSEC=3600
MINUTESEC=60
year=int(input("Please enter the year in which you were born: "))
month=int(input("Please enter the month you were born: "))
day=int(input("Please enter the day you were born: "))
hour=int(input("Please enter the hour you were born: "))
minute=int(input("Please enter the minute you were born: "))
second=int(input("Please enter the second you were born: "))
year_calc=(year*YEARSEC)
month_calc=(month*MONTHSEC)
day_calc=(day*DAYSEC)
hour_calc=(hour*HOURSEC)
minute_calc=(minute*MINUTESEC)
s=(1000000000+year_calc+month_calc+day_calc+hour_calc+minute_calc+second)
year_num=int((s/YEARSEC))
s=(s-(year_num*YEARSEC))
month_num=int((s/MONTHSEC))
s=(s-(month_num*MONTHSEC))
day_num=int((s/DAYSEC))
s=(s-(DAYSEC*day_num))
hour_num=int((s/HOURSEC))
s=(s-(HOURSEC*hour_num))
minute_num=int((s/MINUTESEC))
s=(s-(MINUTESEC*minute_num))
print("You will turn 1 000 000 000 seconds old on: %04d/%02d/%02d %02d:%02d:%02d" %(year_num,month_num,day_num,hour_num,minute_num,s))
答案 0 :(得分:1)
时间计算很棘手。例如,几个月都没有30天。小时,分钟和秒从0开始编号,但是日期和月份从1开始编号,在计算中创建一个错误(提示,请求月份,然后减去一个,执行所有计算,然后添加一次再显示时)。你也没有考虑到闰年。
最好使用内置工具,如果只是检查你最终的作业答案,虽然看起来老师说要假设30天的月份; ^)
>>> import datetime
>>> birthday = datetime.datetime(1993,11,05,0,0,0)
>>> billion = birthday + datetime.timedelta(seconds=1000000000)
>>> billion.ctime()
'Mon Jul 14 01:46:40 2025'
答案 1 :(得分:1)
虽然我没有全部测试,但我认为你不能得到12月和30日。
你应该加1到day_num
和month_num
导致月和日从1开始而不是0。
print("You will turn 1 000 000 000 seconds old on: %04d/%02d/%02d %02d:%02d:%02d" %(year_num,month_num+1,day_num+1,hour_num,minute_num,s))