Skip to content

Instantly share code, notes, and snippets.

@dong-zeyu
Created May 26, 2022 15:59
Show Gist options
  • Save dong-zeyu/b2eda3529a873c2c26937977e830ba95 to your computer and use it in GitHub Desktop.
Save dong-zeyu/b2eda3529a873c2c26937977e830ba95 to your computer and use it in GitHub Desktop.
def days_hours_minutes_seconds(td):
seconds = td.total_seconds()
if seconds < 0:
seconds = -seconds
suffix = "later"
else:
suffix = "ago"
seconds = int(seconds)
if seconds < 60:
return f"{seconds}s {suffix}"
elif seconds < 3600:
minutes = seconds//60
if minutes < 10:
return f"{minutes}m {seconds%60}s {suffix}"
else:
return f"{minutes}m {suffix}"
elif seconds < 86400:
hours = seconds//3600
if hours < 6:
return f"{hours}h {(seconds%3600)//60}m {suffix}"
else:
return f"{hours}h {suffix}"
else:
days = seconds//86400
if days < 3:
return f"{days}d {(seconds%86400)//3600}h {suffix}"
else:
return f"{days}d {suffix}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment