Skip to content

Instantly share code, notes, and snippets.

@HugoPresents
Last active December 18, 2015 22:09
Show Gist options
  • Save HugoPresents/5852244 to your computer and use it in GitHub Desktop.
Save HugoPresents/5852244 to your computer and use it in GitHub Desktop.
Python time stamp to duration
import time
from math import ceil
def time2duration(stamp):
# 对当前时间向上取整,防止出现负数~
stamp = int(ceil(stamp))
cur_time = int(ceil(time.time()))
during = cur_time - stamp
if during < 30:
return str(during) + ' 秒前'
if during < 60:
return '半分钟前'
if during < 3600:
return str(int(during/60)) + ' 分钟前'
if during < 24*3600:
return str(int(during/3600)) + ' 小时前'
if during < 365*24*3600:
return str(int(during/(24*3600))) + ' 天前'
#return str(int(during/(24*3600))) + '天前'
ltime = time.localtime(stamp)
return time.strftime("%Y-%m-%d %H:%m:%S %p", ltime)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment