Skip to content

Commit

Permalink
Added new util to Tgram.utils, readable_time
Browse files Browse the repository at this point in the history
  • Loading branch information
9v2 committed Oct 11, 2024
1 parent 8997e9f commit 05c7427
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions tgram/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from .file_id import decode_file_id, FILE_TYPES, SUPPORTED_FILE_TYPES_TO_SEND
from .files import get_file_name, get_file_path
from .json_ import Json
from .readable_time import readable_time
from .mention import Mention
from .parsers import markdown_unparse, html_unparse, String
from .types import message_origin_parse, convert_input_media
Expand Down Expand Up @@ -31,4 +32,5 @@
"String",
"message_origin_parse",
"convert_input_media",
"readable_time"
]
32 changes: 32 additions & 0 deletions tgram/utils/readable_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import datetime

def readable_time(timestamp):
"""
Converts a timestamp into a human-readable time-ago format.
Parameters:
timestamp (int): Unix timestamp or datetime object.
Returns:
str: Time ago in words (e.g., '5 minutes ago').
"""
if isinstance(timestamp, int):
timestamp = datetime.datetime.fromtimestamp(timestamp)
delta = datetime.datetime.now() - timestamp

if delta.days > 365:
years = delta.days // 365
return f"{years} year(s) ago"
elif delta.days > 30:
months = delta.days // 30
return f"{months} month(s) ago"
elif delta.days > 0:
return f"{delta.days} day(s) ago"
elif delta.seconds > 3600:
hours = delta.seconds // 3600
return f"{hours} hour(s) ago"
elif delta.seconds > 60:
minutes = delta.seconds // 60
return f"{minutes} minute(s) ago"
else:
return "Just now"

0 comments on commit 05c7427

Please sign in to comment.