[英]How to deal with 0 in modulo in python
我想創建代碼,根據經過的小時數告訴我它的日期。
我不想導入任何只想自己計算的庫。 我希望代碼靈活,並且可以處理任何卑鄙的事情(一年中的簡單天數),nohiod(一天中的小時數)和我要給出的月數。 唯一的絕對值是小時,它始終是相同的,並且有60分鍾。
下面的代碼確實很好用,但是問題是,我有12(0-12)而不是12個月,而且我不知道如何以最有效的方式處理0。 下面的例子。 我的小時數為我提供0天0個月和正確的年份(2016)。
dev = True
# simple number of days in year
snodiy = 365.25
# number of hours in one day
nohiod = 24
# total hours passed
# 17672256 current year
thp = 17672257
dayc = 30 # number of days in a month #
# get date
def gd():
year = (thp / snodiy) / nohiod
rest = thp % (snodiy * nohiod)
if dev:
print("dev year rest:", rest)
month = rest / (dayc * nohiod)
rest %= (dayc * nohiod)
if dev:
print("dev month rest:", rest)
day = rest / nohiod
rest %= nohiod
if dev:
print("dev hour rest:", rest)
hour = rest
if dev:
print("Year:", "%d" % year)
print("Month:", "%d" % month)
print("Day:", "%d" % day)
print("Hour:", "%d" % hour)
print("Hour:", "%d" % hour, "of", "%d" % day, "%d" % month, "%d" % year)
gd()
我將假設我們不受現實時間問題的所有約束,例如leap年,leap秒,DST等。如果是的話,那么您將承擔一項極其重要的任務,並且其他人提到您最好將其留給圖書館。 繼續...
問題的實質是您隱含的假設,即一年恰好是12個月。 您將一年定義為365.25 * 24 = 8766
小時。 您將一個月定義為30 * 24 = 720
小時長。 12個月為720 * 12 = 8640
小時。 您的年份超過12個月,因此計算得出的第13個月也就不足為奇了。
你太束縛了。 您需要做以下三件事之一:
dayc = snodiy / 12
snodiy = dayc * 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.