开发者

Regarding simple python date calc

I am trying to find out when someone will turn 1 billion seconds old. the user inputs when they were born. These values are then converted to seconds and then I add 1 billion seconds and convert back into a date. However, when I enter certain dates, python seems to mess up. Such an example is 1993/11/05 00:00:00 where python says the user will turn in the 0th month. Note I cant use if/else or datetime.

Heres my code:

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


mon开发者_JAVA技巧th_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))


Though I have not test it all, I think you can not get Dec and day 30. You should plus 1 to day_num and month_num cause month and day start from 1 not 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))


Time calculations are tricky. Months don't all have 30 days, for example. Hours, minutes, and seconds are numbered starting from 0, but days and months are numbered starting from 1, creating off-by-one bugs in your calculations (hint, ask for month, then subtract one, do all the calculations, then add one when displaying it again). You aren't accounting for leap years either.

Best to use built-in tools, if only to check your eventual homework answer, although it looks like the teacher said to assume 30-day months ;^)

>>> 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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜