Time Ago 포매터
날짜와 타임스탬프를 '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 agoComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.