Last active
February 27, 2021 18:59
-
-
Save Shaun420/92ebce7b8066de54c22d31e3d7acd858 to your computer and use it in GitHub Desktop.
Returns the time passed since an unix timestamp as a formatted string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, math | |
# Sample timestamp to test. | |
dTs = 1610033721 | |
def returnTimeSince(unixtimestamp: int) -> str: | |
# String which will contain formatted time. | |
timesince = "" | |
# Get the difference between the argument timestamp and current timestamp. | |
# Note: time.time() returns a float. | |
diffTs = round(time.time()) - unixtimestamp | |
if (diffTs / 31536000) >= 1: | |
# Value can be expressed in years. | |
years = math.floor(diffTs / 31536000) | |
timesince = "{0} {1}".format(years, "year" if years == 1 else "years") | |
elif ((diffTs * 100) / 262800288) >= 1: | |
# Value can be displayed in months. | |
months = math.floor((diffTs * 100) / 262800288) | |
timesince = "{0} {1}".format(months, "month" if months == 1 else "months") | |
elif (diffTs / 604800) >= 1: | |
# Value can be displayed in weeks. | |
weeks = math.floor(diffTs / 604800) | |
timesince = "{0} {1}".format(weeks, "week" if weeks == 1 else "weeks") | |
elif (diffTs / 86400) >= 1: | |
# Value can be displayed in days. | |
days = math.floor(diffTs / 86400) | |
timesince = "{0} {1}".format(days, "day" if days == 1 else "days") | |
elif (diffTs / 3600) >= 1: | |
# Value can be displayed in hours. | |
hours = math.floor(diffTs / 3600) | |
timesince = "{0} {1}".format(hours, "hour" if hours == 1 else "hours") | |
elif (diffTs / 60) >= 1: | |
# Value can be displayed in minutes. | |
minutes = math.floor(diffTs / 60) | |
timesince = "{0} {1}".format(minutes, "minute" if minutes == 1 else "minutes") | |
else: | |
# Value can be displayed in seconds only. | |
timesince = "{0} {1}".format(diffTs, "second" if diffTs == 1 else "seconds") | |
# To indicate that it is the end of formatted string. | |
timesince += " ago." | |
return timesince | |
print("Time passed since test: {0}".format(returnTimeSince(dTs))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment