时间人性化(案例)
import datetime
import pendulum
# 把需要转换的时间字符串转为datetime对象,再转为字符串
now = datetime.datetime.strptime('2022-11-11 14:13:32', '%Y-%m-%d %H:%M:%S')
new_str = now.strftime('%Y-%m-%d %H:%M:%S')
# 把字符串转为pendulum时间对象
pt = pendulum.parse(new_str, tz='Asia/Shanghai')
pendulum.set_locale('zh')
# 使用方法diff_for_humans()输出当前人性化时间
print(pt.diff_for_humans())
# result打印 2个月前
人性化(基础讲解)
import pendulum
pendulum.now().subtract(days=1).diff_for_humans()
# '1 day ago'
pendulum.now().diff_for_humans(pendulum.now().subtract(years=1))
# '1 year after'
dt = pendulum.datetime(2011, 8, 1)
dt.diff_for_humans(dt.add(months=1))
# '1 month before'
dt.diff_for_humans(dt.subtract(months=1))
# '1 month after'
pendulum.now().add(seconds=5).diff_for_humans()
# '5 seconds from now'
pendulum.now().subtract(days=24).diff_for_humans()
# '3 weeks ago'
pendulum.now().subtract(days=24).diff_for_humans(absolute=True)
# '3 weeks'
pendulum.set_locale('zh')
pendulum.now().subtract(days=24).diff_for_humans()
# '3周前'
pendulum.now().add(seconds=5).diff_for_humans()
# '5秒钟后'
oneday = pendulum.now().diff(pendulum.now().add(days=1))
oneday.in_words()
# '1天'