需要帮助将总分钟数转换为小时和分钟格式

时间:2014-10-21 14:08:07

标签: python python-3.x integer divide

我需要帮助使用余数运算符将其转换为小时和分钟格式。我对python和编码一般比较陌生,所以非常感谢帮助。

#Define the value of our variables 
numberOfEpisodes = 13
minutesPerEpisode = 42

#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//minutesPerHour

#Display the output 
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.') print('This is equivalent to', equivalency)

这是我目前所拥有的,我能够获得所需的小时数,但我无法弄清楚如何调整代码以包括剩余的分钟数。

很抱歉,如果我没有多大意义,但希望你能理解。

3 个答案:

答案 0 :(得分:3)

您可以使用//整数除法和%模数作为余数。 (您可以阅读有关Python intfloat部门here

的更多信息
>>> numberOfEpisodes = 13
>>> minutesPerEpisode = 42
>>> totalMinutes = numberOfEpisodes * minutesPerEpisode
>>> totalMinutes
546

>>> minutesPerHour = 60
>>> totalHours = totalMinutes // minutesPerHour
>>> totalHours
9

>>> remainingMinutes = totalMinutes % minutesPerHour
>>> remainingMinutes
6

结果

>>> print('{} episodes will take {}h {}m to watch.'.format(numberOfEpisodes,totalHours, remainingMinutes))
13 episodes will take 9h 6m to watch.

答案 1 :(得分:1)

使用模运算符%

#Define the value of our variables                                                                                                                                                                                                                                            
numberOfEpisodes = 13
minutesPerEpisode = 42

#Calculate the results                                                                                                                                                                                                                                                        
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//60
minutes= totalMinutes%60

#Display the output                                                                                                                                                                                                                                                           
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.')
print('This is equivalent to', equivalency,minutes)

答案 2 :(得分:1)

查看日期时间模块文档中的timedelta文档。您可以将持续时间创建为以分钟为单位的时间增量,然后当您想要显示它时,您可以要求timedelta以您想要的任何格式提供它。您可以使用算术计算来获得小时和分钟,但是如果您需要使用此数据来计算日期和时间,例如要知道节目将在09:00开始时将结束的时间,您将拥有许多额外的步骤,而不仅仅是使用timedelta。