How to deal with 0 in modulo in python
<p>I want to create code that tells me what date it is based on how many hours passed.</p>

<p>I don't want to import any libraries I just want to calculate this myself. I want code to be flexible and work with whatever snodiy (simple number of days in year), nohiod (number of hours in one day) and number of months I'll give it. Only absolute is hour which will always be the same and have 60 minutes.</p>

<p>Code below works really well but the problem is that instead of 12 months I have 13 (0-12) and I don't know how to deal with 0 in most efficient manner. Example below. I have number of hours that gives me 0 days 0 months and correct year (2016).</p>

<pre><code>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()
</code></pre>

<p><em>I'm going to assume we're not bound by all the constraints of real-world time issues like leap years, leap seconds, DST, etc. If we are, you're taking on an extremely non-trivial task, and as others have mentioned you're probably best off leaving it to libraries. Moving on...</em></p>

<p>The essence of the problem is your implicit assumption that a year is exactly 12 months. You define a year as <code>365.25 * 24 = 8766</code> hours long. You define a month as <code>30 * 24 = 720</code> hours long. 12 months would be <code>720 * 12 = 8640</code> hours. Your year is longer than 12 months, so it's not surprising you're getting a 13th month in your calculations.</p>

<p>You're overconstrained. You need to do one of three things:</p>

<ul>
<li><code>dayc = snodiy / 12</code></li>
<li><code>snodiy = dayc * 12</code></li>
<li>Accept (and be able to deal with) the fact that there are not exactly 12 months in a year.</li>
</ul>

python modulo