【问题标题】:Regarding simple python date calc关于简单的python日期计算
【发布时间】:2011-12-01 03:57:54
【问题描述】:

我想知道一个人什么时候会达到 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))

【问题讨论】:

  • 在没有datetime 的情况下正确执行此操作将是一个丑陋的混乱......为什么你说你不能使用它?
  • 这可能是他的家庭作业;)

标签: python date-arithmetic


【解决方案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'

【讨论】:

  • 我知道日期时间将是做到这一点的最佳方式。但我不能。是的,它说假设一个月有 30 天。但是非常感谢
【解决方案2】:

虽然我还没有全部测试,但我认为你不能得到 12 月和 30 天。 您应该将 1 加到 day_nummonth_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))

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 2011-04-30
    • 1970-01-01
    • 2011-12-11
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多