Python Datetime将timedelta舍入到最近的最大单位

时间:2018-06-26 17:11:01

标签: python python-3.x datetime formatting

我一直在做一个论坛来学习。每个帖子都有一个时间戳,我将其转换为一个timedelta(多少时间之前)。我想这样输出时间:

If it's    <     1 minute                       display it in seconds
If it's    >=    1 minute   and    < 1 hour     display it in minutes
If it's    >=    1 hour     and    < 1 day      display it in hours
If it's    >=    1 day      and    < 1 week     display it in days
If it's    >=    1 week     and    < 1 month    display it in weeks
If it's    >=    1 month    and    < 1 year     display it in months
If it's    >=    1 year                         display it in years

在python和datetime中执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

使用第三方库。例如,readabledelta是一个timedelta子类,它打印出易于阅读的内容。

>>> from readabledelta import readabledelta
>>> from datetime import timedelta
>>> print(readabledelta(timedelta(seconds=1)))
1 second
>>> print(readabledelta(timedelta(seconds=60)))
1 minute
>>> print(readabledelta(timedelta(seconds=60*60)))
1 hour
>>> print(readabledelta(timedelta(seconds=60*60*24)))
1 day
>>> print(readabledelta(timedelta(seconds=60*60*24*7)))
1 week

您不能轻易使用数月或数年,因为单位长度的定义不明确(一个月可能是28-31天,而一年则可能是365-366天)。