簡體   English   中英

如何在Python中使用%將秒轉換為分鍾和秒

[英]How do I use % to convert seconds to minutes AND seconds in Python

def main():
    import math
    print('Period of a pendulum')
    Earth_gravity = 9.8
    Mars_gravity = 3.7263
    Jupiter_gravity = 23.12
    print('     ')
    pen = float(input('How long is the pendulum (m)? '))
    if pen < 0:
        print('illegal length, length set to 1')
        pen = 1
        period1 = (2 * 3.14159265359) * math.sqrt(pen / Earth_gravity)
        period2 = (2 * 3.14159265359) * math.sqrt(pen / Mars_gravity)
        period3 = (2 * 3.14159265359) * math.sqrt(pen / Jupiter_gravity)        
        print('     ')
        print('The period is', round(period1,3))
        minutes1 = period1 / 60
        minutes2 = period1 / 60
        minutes3 = period1 / 60
        seconds1 = minutes1 % 60
        seconds2 = minutes2 % 60
        print('or', round(minutes1,1), 'minutes and', seconds, 'seconds on 
Earth')
        print('     ')
        print('The period is', round(period2,3))
        print('or', round(minutes2,1), 'minutes and', seconds, 'seconds on 
Mars')
        print('     ')
        print('The period is', round(period3,3))
        print('or', round(minutes3,1), 'minutes and', seconds, 'seconds on 
Jupiter')        
    else:
        period1 = (2 * 3.14159265359) * math.sqrt(pen / Earth_gravity)
        period2 = (2 * 3.14159265359) * math.sqrt(pen / Mars_gravity)
        period3 = (2 * 3.14159265359) * math.sqrt(pen / Jupiter_gravity)        
        print('     ')
        print('The period is', round(period1,3))
        minutes1 = period1 // 60
        minutes2 = period2 // 60
        minutes3 = period3 // 60
        seconds1 = minutes1 % 60
        seconds2 = minutes2 % 60
        seconds3 = minutes3 % 60
        print('or', round(minutes1,1), 'minutes and', seconds1, 'seconds on 
Earth')
        print('     ')
        print('The period is', round(period2,3))
        print('or', round(minutes2,1), 'minutes and', seconds2, 'seconds on 
Mars')
        print('     ')
        print('The period is', round(period3,3))
        print('or', round(minutes3,1), 'minutes and', seconds3, 'seconds on Jupiter')        

main()

好吧,我需要將秒轉換為秒和分鍾。 我不確定如何使用%來獲取輸出的秒和分鍾。 我需要在此使用//和%。 我對此很陌生,因此對它草率或過大表示歉意。 混亂的區域是包含%的行。 謝謝!

您可以簡單地使用divmod返回整數除數和模,非常適合您的情況:

>>> seconds = 1000
>>> minutes, seconds = divmod(seconds, 60)
>>> hours, minutes = divmod(minutes, 60)
>>> days, hours = divmod(hours, 24)
>>> days, hours, minutes, seconds
(0, 0, 16, 40)

似乎您只需要第一行minutes, seconds = divmod(seconds, 60)但我想展示一下如果還有更多的轉化,該如何使用。 :)

整數將舍入到最接近的整數。 %或模運算符僅報告除法運算的其余部分。

因此135%60返回15。這是因為60兩次進入135,但其余15小於60。60進入135的兩次均未返回,因此您需要使用標准除法來找到該值運營商。

您可以除以60得到分鍾,然后還可以使用取模運算符返回剩余的秒數。

time = 135

minutes = time / 60
seconds = time % 60

print minutes
print seconds

回報

2
15

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM