Alternative
Amazon
Article
Writing
Art
AI
Angular
Photoshop
Premiere
Animal Crossing
Blog
Story
Android
Android Studio
Davinci Resolve
CSS
Clipchamp
ChatGPT
Crypto
DALL-E
Discord
Davinci Resolve
Davinci Resolve 18
Dream Studio
Express
Filmora
Flutter
PC Games
Git
GPT
GPT3
GPT4
GTA
GTA 6
Ghost Together
Ghost Together
HTML
iOS
iMovie
Illustrator
JavaScript
Mac
Mongo
Midjourney
Minecraft
Node.js
NBA 2k24
OSX
PHP
Palworld
Python
Playground AI
Roblox
React
Recipe (Cooking)
React Native
Semicolon.dev
Starfield PC Game
Snapchat
Steam
Stable Diffusion
SVG
Threads
Text To Image (AI)
VSCode
Vim
Web Development
Windows
WebGL

Convert time difference to elapsed time

Create a function that converts a time interval between two timestamps to a more human-readable "elapsed time" format, similar to how social media apps do it.

import time
import threading

# create a table measuring key intervals in seconds
table = [1,             # seconds (1 to avoid division by 0)
         60,            # 1 minute
         3600,          # 1 hour
         3600*24,       # 1 day
         36002430,    # 1 month
         36002430*12] # 1 year

# list to hold interval endings

endings = ["s", "m", "h", "d", "mo", "y"]

def seconds2elapsed(t): difference = abs(time.time() - t) #convert to integer (truncate decimal point) difference = int(difference) if (difference == 0) return "now"

i = 5

# iterate over table backwards for interval in reversed(table): # if difference is greater: t = table[i] v = (difference - difference % t)) / t # early exit from function return f"{int(v){endings[i]}}" #python's for loops don't have indexing

(unless used with enumerable, iterate manually)

i -= 1

Let's test the function!

since = time.time()

def every3seconds(): # execute this function every 3.0 seconds threading.Timer(3.0, every3seconds).start() print(f"{seconds2elapsed(since)}") # trigger the timer every3seconds()

Output:

3s

6s

9s

12s

15s

18s

21s

24s

27s

30s

33s

36s

39s

42s

45s

48s

51s

54s

57s

1m

1m

1m

1m 1m
Write For Us
Sign Up Now  -  It's Free!

Convert time difference to elapsed time

Comments (2) New! (You can now post comments on articles!)

(By posting a comment you are registering a Ghost Together account.)
Register
Register
Post It
DM Coming Soon
f f