跳到内容
🛠️ToolsShed

时间格式化工具

将日期和时间戳转换为'3天前'或'2个月后'等相对时间字符串。

关于此工具

时间前格式化工具将绝对日期和时间戳转换为人类自然理解的相对时间描述,如「3天前」或「2个月后」。这种格式在聊天应用程序、社交媒体、活动提示和项目管理工具中特别有用,因为在这些场景中,显示某件事何时发生比显示精确日期时间更重要。

只需将任何日期或时间戳输入到工具中,它就会立即显示那个时刻距离现在有多久或距离未来还有多远。格式化工具智能地处理不同的时间规模——秒、分钟、小时、天、月和年——自动选择最具可读性的单位。

这个工具对于构建实时应用程序的开发者、管理帖子和更新的内容创建者,以及任何想要一目了然地理解时间差异而无需进行心算的人都是无价的。

常见问题

代码实现

from datetime import datetime, timezone

def time_ago(past: datetime, now: datetime = None) -> str:
    """Return human-readable relative time string."""
    if now is None:
        now = datetime.now(timezone.utc)
    diff = now - past
    total_seconds = int(diff.total_seconds())
    if total_seconds < 0:
        return "in the future"

    minutes = total_seconds // 60
    hours = minutes // 60
    days = hours // 24
    months = days // 30
    years = days // 365

    if total_seconds < 60:
        return f"{total_seconds} second{'s' if total_seconds != 1 else ''} ago"
    elif minutes < 60:
        return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
    elif hours < 24:
        return f"{hours} hour{'s' if hours != 1 else ''} ago"
    elif days < 30:
        return f"{days} day{'s' if days != 1 else ''} ago"
    elif months < 12:
        return f"{months} month{'s' if months != 1 else ''} ago"
    else:
        return f"{years} year{'s' if years != 1 else ''} ago"

# Examples
from datetime import timedelta
now = datetime(2025, 6, 15, 12, 0, 0, tzinfo=timezone.utc)
print(time_ago(now - timedelta(seconds=30), now))   # 30 seconds ago
print(time_ago(now - timedelta(minutes=45), now))   # 45 minutes ago
print(time_ago(now - timedelta(days=3), now))       # 3 days ago
print(time_ago(now - timedelta(days=400), now))     # 1 year ago

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.