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

Qwe*_*rty 5 python formatting datetime python-3.x

我一直在创建一个论坛作为一种学习经历。我为每个帖子都有一个时间戳,我将其转换为时间增量(这是多少时间之前)。我想像这样输出时间:

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
Run Code Online (Sandbox Code Playgroud)

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

wim*_*wim 1

使用第三方库。例如,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
Run Code Online (Sandbox Code Playgroud)

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