You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Epoch时间戳转换为“X年前”类可读相对时间?

问题:将Epoch时间戳转换为相对时间表述

我希望将Epoch时间戳转换为类似「1575135888 ==> 3年前」的可读相对时间格式。目前我使用以下代码:

import datetime

date_c = datetime.datetime.fromtimestamp(1575135888)
print(datetime.date.today())  
print(date_c) 

运行后得到当前日期2022-12-09和转换后的具体日期2019-11-30 18:44:48,但不清楚如何将其转换为“3年前”这类相对时间表述。


解决方案

要实现相对时间转换,核心是计算目标时间与当前时间的时间差,再根据差值量级输出对应表述。以下提供两种实现方式:

1. 原生datetime手动实现

通过计算年、月、日等维度的差值,处理边界情况后输出对应文本:

import datetime

def epoch_to_relative(epoch_timestamp):
    target_dt = datetime.datetime.fromtimestamp(epoch_timestamp)
    now_dt = datetime.datetime.now()
    
    # 计算年份差,需考虑月日是否过了当年对应日期
    year_diff = now_dt.year - target_dt.year
    if (now_dt.month, now_dt.day) < (target_dt.month, target_dt.day):
        year_diff -= 1
    if year_diff > 0:
        return f"{year_diff}年前"
    
    # 计算月份差,需考虑日期是否过了当月对应日期
    month_diff = (now_dt.year - target_dt.year)*12 + now_dt.month - target_dt.month
    if now_dt.day < target_dt.day:
        month_diff -= 1
    if month_diff > 0:
        return f"{month_diff}个月前"
    
    # 计算天数及更小单位差值
    delta = now_dt - target_dt
    if delta.days > 0:
        return f"{delta.days}天前"
    
    hours = delta.seconds // 3600
    if hours > 0:
        return f"{hours}小时前"
    
    minutes = (delta.seconds % 3600) // 60
    if minutes > 0:
        return f"{minutes}分钟前"
    
    return "刚刚"

# 测试示例
print(f"1575135888 ==> {epoch_to_relative(1575135888)}")

以2022-12-09的时间为准,运行后会输出:1575135888 ==> 3年前

2. 第三方库简化实现

如果不想手动处理复杂的时间差逻辑,可使用arrow库的humanize方法自动生成相对时间:

import arrow

def epoch_to_relative(epoch_timestamp):
    target_time = arrow.get(epoch_timestamp)
    return target_time.humanize(locale='zh')

# 测试示例
print(f"1575135888 ==> {epoch_to_relative(1575135888)}")

运行后同样会输出3年前这类符合需求的结果,该方法支持多语言,且自动处理不同时间量级的表述。使用前需先安装库:pip install arrow

内容的提问来源于stack exchange,提问作者jame the spear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:35:13