问:编写一个要求用户输入秒数的程序,其工作原理如下:
,
到目前为止,我所拥有的:
def time():
sec = int( input ('Enter the number of seconds:'.strip())
if sec <= 60:
minutes = sec // 60
print('The number of minutes is {0:.2f}'.format(minutes))
if sec (<= 3600):
hours = sec // 3600
print('The number of minutes is {0:.2f}'.format(hours))
if sec <= 86400:
days = sec // 86400
print('The number of minutes is {0:.2f}'.format(days))
return
发布于 2014-07-03 07:02:05
这个tidbit对于以不同的粒度显示已用时间很有用。
我个人认为,效率的问题在这里实际上是没有意义的,只要没有做一些非常低效的事情。过早的优化是很多坏事的根源。这已经足够快了,它永远不会成为你的瓶颈。
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def display_time(seconds, granularity=2):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])
..and这提供了不错的输出:
In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'
In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'
发布于 2010-10-29 11:30:46
这会将n秒转换为d天、h小时、m分钟和s秒。
from datetime import datetime, timedelta
def GetTime():
sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
d = datetime(1,1,1) + sec
print("DAYS:HOURS:MIN:SEC")
print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))
发布于 2016-05-10 17:26:10
要将秒(字符串)转换为日期时间,这也可能会有所帮助。你可以得到天数和秒数。秒可以进一步转换为分钟和小时。
from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)
https://stackoverflow.com/questions/4048651
复制相似问题