(Python) Using modulo to get the remainder from changing secs, to hrs and minutes

こ雲淡風輕ζ 提交于 2019-12-25 04:27:50

问题


I'm currently new to learning python and stumbled upon this problem:

Exercise 2-7 Get the Time Write an algorithm that reads the amount of time in seconds and then displays the equivalent hours, minutes and remaining seconds. • One hour corresponds to 60 minutes. • One minute corresponds to 60 seconds.

Here's how I wrote it:

def amount_time(t):
  h = t//3600
  m = int((t/3600 - h)*60)
  s = int(((t/3600 - h)*60 - m)*60)
  print("Number of hours:",h)
  print("Number of minutes:",m)
  print("Number of Seconds:", s)
amount_time(5000)

I was told there was an easier way to write it using modulo to get the remainder for the minutes and seconds, could someone help? Thanks!


回答1:


This is just "out of my head", because I got no testing system I could use right now.

def amount_time(t):
    print("Number of Seconds:", t % 60)
    print("Number of Minutes:", (t // 60) % 60)
    print("Number of Hours:", (t // 3600))

What "t % 60" does:

  1. take t, divide it by 60
  2. remove everthing left of the dot
  3. multiply with 60

With numbers:

  1. 5000 / 60 = 83.33333
  2. => 0.33333
  3. 0.33333 * 60 = 20



回答2:


Your calculation of minuts doesnt work correct, you use Modulo with the hours. You could do the same with minutes as you did wirh seconds instead:

m =     (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds

and to build the result string there are better ways, f.e.

print '{}:{}:{}.{}'.format(h,m,s,ms)

You find more ways and options to Format, if you look here:

python dokumentation for string formatting



来源:https://stackoverflow.com/questions/40084887/python-using-modulo-to-get-the-remainder-from-changing-secs-to-hrs-and-minute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!