具体日期,史学家在行。对于我们,“昨天”,“几个月前”,比较舒服。通常论坛,评论的时间使用这种格式。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
def friendly_time(timestamp):
"""
友好的时间展示
:param timestamp:
:return:
"""
current_time = int(time.time())
time_distance = abs(current_time - timestamp)
if time_distance < 60:
return "%s秒前" % time_distance
elif time_distance < 60 * 60:
return "%s分钟前" % (time_distance / 60)
elif time_distance < 60 * 60 * 24:
return '%s小时前' % (time_distance / 60 / 60)
elif time_distance < 60 * 60 * 24 * 2:
return "昨天"
elif time_distance < 60 * 60 * 24 * 30:
return '%s天前' % (time_distance / 60 / 60 / 24)
else:
return time.strftime("%Y年%m月%d日 %H:%M'", time.localtime(timestamp))
if __name__ == "__main__":
print friendly_time(int(time.time())+3700)
1小时前