Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Last active February 1, 2018 08:24
Show Gist options
  • Save Ivlyth/1736cdcc526ee189d2bd285b27583710 to your computer and use it in GitHub Desktop.
Save Ivlyth/1736cdcc526ee189d2bd285b27583710 to your computer and use it in GitHub Desktop.
将秒数转化为可读性更强的秒数方式
'''
将秒数转换为可读性更强的表述方式
eg:
```
In [4]: print seconds_to_human_readable(33)
33 秒
In [5]: print seconds_to_human_readable(60 * 3 + 2)
3 分钟, 2 秒
In [6]: print seconds_to_human_readable(3600 * 2 + 60 * 3 + 2)
2 小时, 3 分钟, 2 秒
In [7]: print seconds_to_human_readable(3600 * 24 * 3 + 3600 * 2 + 60 * 3 + 2)
3 天, 2 小时, 3 分钟, 2 秒
```
'''
def seconds_to_human_readable(seconds, delimiter=', '):
'''
将秒数转换为人可读文本
:param seconds:
:param delimiter: ', '
:return:
'''
seconds = int(seconds)
if seconds == 0:
return u'0秒(极速)'
elif seconds < 60: # [0, 1分钟)
return u'%s 秒' % seconds
elif 60 <= seconds < 60 * 60: # [1分钟, 1小时)
minutes = seconds / 60
remain_seconds = seconds - minutes * 60
if remain_seconds == 0:
return u'%s 分钟' % minutes
else:
return u'%s 分钟%s%s 秒' % (minutes, delimiter, remain_seconds)
elif 60 * 60 <= seconds < 24 * 60 * 60: # [1小时, 1天)
hours = seconds / (60 * 60)
remain_seconds = seconds - hours * 60 * 60
remain_desc = seconds_to_human_readable(remain_seconds)
if remain_desc:
return u'%s 小时%s%s' % (hours, delimiter, remain_desc)
else:
return u'%s 小时' % hours
else: # [1天, )
days = seconds / (24 * 60 * 60)
remain_seconds = seconds - (days * 24 * 60 * 60)
remain_desc = seconds_to_human_readable(remain_seconds)
if remain_desc:
return u'%s 天%s%s' % (days, delimiter, remain_desc)
else:
return u'%s 天' % days
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment