improved the time format function some more

This commit is contained in:
Luke Rogers 2013-11-30 23:18:45 +13:00
parent 78912b908f
commit f55c8f8d4e

View file

@ -17,17 +17,17 @@ def plural(num=0, text=''):
return "{:,} {}{}".format(num, text, "s"[num==1:]) return "{:,} {}{}".format(num, text, "s"[num==1:])
def time_simple(seconds): def format_time(seconds, accuracy=3, simple=False):
out = "" if simple:
if seconds / 3600: # > 1 hour periods = [
out += '%dh ' % (seconds / 3600) ('y', 60*60*24*365),
if seconds / 60: ('m', 60*60*24*30),
out += '%dm ' % (seconds / 60 % 60) ('d', 60*60*24),
out += "%ds" % (seconds % 60) ('h', 60*60),
return out ('m', 60),
('s', 1)
]
def time_complex(seconds): else:
periods = [ periods = [
(' year', 60*60*24*365), (' year', 60*60*24*365),
(' month', 60*60*24*30), (' month', 60*60*24*30),
@ -38,14 +38,22 @@ def time_complex(seconds):
] ]
strings = [] strings = []
i = 0
for period_name, period_seconds in periods: for period_name, period_seconds in periods:
if i < accuracy:
if seconds > period_seconds: if seconds > period_seconds:
period_value, seconds = divmod(seconds,period_seconds) period_value, seconds = divmod(seconds,period_seconds)
if period_value == 1: i += 1
if period_value == 1 or simple:
strings.append("%s%s" % (period_value, period_name)) strings.append("%s%s" % (period_value, period_name))
else: else:
strings.append("%s%ss" % (period_value, period_name)) strings.append("%s%ss" % (period_value, period_name))
else:
break
if simple:
return " ".join(strings)
else:
return text.get_text_list(strings, "and") return text.get_text_list(strings, "and")
@ -63,7 +71,7 @@ def get_video_description(video_id):
return out return out
length = data['duration'] length = data['duration']
out += ' - length \x02{}\x02'.format(time_simple(length)) out += ' - length \x02{}\x02'.format(format_time(length, simple=True))
if 'ratingCount' in data: if 'ratingCount' in data:
# format # format
@ -145,8 +153,8 @@ def youtime(inp):
views = data['viewCount'] views = data['viewCount']
total = int(length * views) total = int(length * views)
length_text = time_simple(length) length_text = format_time(length, simple=True)
total_text = time_complex(total) total_text = format_time(total)
return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \ return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
'a total run time of {}!'.format(data['title'], length_text, views, \ 'a total run time of {}!'.format(data['title'], length_text, views, \