Göreli Zaman Biçimleyici
Tarihleri ve zaman damgalarını '3 gün önce' veya '2 ay sonra' gibi göreli zaman dizilerine dönüştürür.
Sıkça Sorulan Sorular
Kod Uygulaması
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.