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

0 投票
3 回答
3381 浏览
提问于 2025-04-28 19:29

我需要帮助,把这个转换成小时和分钟的格式,使用余数运算符。我对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 个回答

1

可以看看 timedelta 的文档,它在日期时间模块里。你可以把时间段当作时间差来创建,单位是分钟。然后当你想要显示这个时间段时,可以让 timedelta 按你想要的格式给你结果。虽然你可以用数学计算来得到小时和分钟,但如果你还需要用这些数据来计算日期和时间,比如想知道如果节目在09:00开始,什么时候结束,那你就得经过很多额外的步骤,而直接使用timedelta会简单很多。

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)
3

你可以使用 // 来进行整数除法,使用 % 来得到余数。想了解更多关于Python中 intfloat 除法的内容,可以点击这里

>>> 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.

撰写回答