'Calculating the minutes since midnight [closed]

Have run into more of a maths problem than code. So far have programmed to retrieve the local time, print the local time as "Current Time: " and then programmed the variables to print "Number of minutes since midnight: ". looks like this

import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print("Current Time: ",current_time)
hour = time.strftime("%H")
minute = time.strftime("%M")
print ("Number of minutes since midnight: ",int(hour)*60+int(minute))

so my output is

Current Time:  22:16:15
Number of minutes since midnight:  1336 

Except a quick google search tells me it's closer to 2,777 minutes since midnight.

This is my first program, so if you're wondering why I want to know how many minutes since midnight it is at any given time without JFGI, I just do. It's been a fun problem to solve so far, and I would hate to leave it unfinished because I don't know the maths I need to know yet.

Thanks in advance!



Solution 1:[1]

I think your code is actually working as intended!

One quick recommendation for an improvement though:

When you call

t = time.localtime()

You're storing the current time in the variable t, but then when you later call

hour = time.strftime("%H")
minute = time.strftime("%M")

you are actually asking the program to fetch the system clock time again twice, rather than using the already stored time value you have in t.

You could instead do the following and access the hour and time values from the t object directly.

import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print("Current Time: ", current_time)
print ("Number of minutes since midnight: ",int(t.tm_hour)*60+int(t.tm_min))

I hope you're enjoying your first steps into programming!

Solution 2:[2]

I believe whatever you googled was incorrect, I tried this out and also got 1336.

current_time = "22:16:15"
hrs, mins, _ = current_time.split(":")
since_midnight = int(hrs) * 60 + int(mins)

The total number of minutes in a day is 1440, so it clearly cant be more than that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ncoish
Solution 2 Anonymous4045