Python:我需要以"1天前“,”2小时前“的格式显示文件修改时间。
有什么东西准备好这么做了吗?它应该是英文的。
发布于 2013-08-25 01:58:48
Jed Smith链接的答案是好的,我用了一年左右,但我认为它可以在几个方面改进:
这是我想出来的:
def PrettyRelativeTime(time_diff_secs):
# Each tuple in the sequence gives the name of a unit, and the number of
# previous units which go into it.
weeks_per_month = 365.242 / 12 / 7
intervals = [('minute', 60), ('hour', 60), ('day', 24), ('week', 7),
('month', weeks_per_month), ('year', 12)]
unit, number = 'second', abs(time_diff_secs)
for new_unit, ratio in intervals:
new_number = float(number) / ratio
# If the new number is too small, don't go to the next unit.
if new_number < 2:
break
unit, number = new_unit, new_number
shown_num = int(number)
return '{} {}'.format(shown_num, unit + ('' if shown_num == 1 else 's'))注意intervals中的每个元组是如何易于解释和检查的:'minute'是60秒;'hour'是60分钟;等等。唯一的错误是将weeks_per_month设置为其平均值;给定应用程序,这应该很好。(请注意,最后三个常量乘以365.242,即每年的天数,这一点一目了然。)
我的函数的一个缺点是它不做"##单位“模式之外的任何事情:”昨天“、”刚才“等都是正确的。话又说回来,最初的帖子没有要求这些花哨的术语,所以我更喜欢我的函数,因为它简洁,而且它的数值常量具有可读性。:)
https://stackoverflow.com/questions/1551382
复制相似问题