From: "1 hour ago", To: timedelta + accuracy - python

Is there a function to 'reverse humanize' times?
For example, given (strings):
'1 minute ago'
'7 hours ago'
'5 days ago'
'2 months ago'
Could return (apologies for the pseudo-code):
datetime.now() - timedelta (1 minute), accuracy (60 seconds)
datetime.now() - timedelta (7 hours), accuracy (1 hour)
datetime.now() - timedelta (5 days), accuracy (1 day)
datetime.now() - timedelta (2 months), accuracy (1 month)

I've been using parsedatetime and it's worked rather well for me. The home page lists some formats it can handle, e.g.:
in 5 minutes
5 minutes from now
2 hours before noon
2 days from tomorrow
The major downside I've found is that it has no sense of timezones.
In case it's worth anything, here's a wrapper function I use, which always returns a datetime object regardless of whether the input string is relative (like all your examples) or fixed:
def parse_datetime(datetime_string):
datetime_parser = parsedatetime.Calendar(parsedatetime_consts.Constants())
timestamp = datetime_parser.parse(datetime_string)
if len(timestamp) == 2:
if timestamp[1] == 0:
raise ValueError(u'Failed to parse datetime: %s' % datetime_string)
timestamp = timestamp[0]
return datetime.fromtimestamp(time.mktime(timestamp))

Can you not just write a simple implementation yourself such as:
import datetime
def parsedatetime(str_val):
parts = str_val.split(' ')
if len(parts) != 3 and parts[2] != 'ago':
raise Exception("can't parse %s" % str_val)
try:
interval = int(parts[0])
except ValueError,e :
raise Exception("can't parse %s" % str_val)
desc = parts[1]
if 'second' in desc:
td = datetime.timedelta(seconds=interval)
elif 'minute' in desc:
td = datetime.timedelta(minutes=interval)
elif 'hour' in desc:
td = datetime.timedelta(minutes=interval*60)
elif 'day' in desc:
td = datetime.timedelta(days=interval)
else:
raise Exception("cant parse %s" % str_val)
answer = datetime.datetime.now - td
return answer
The input doesn't look that varied.

Related

Python Timer Cooldown Example

I'm looking for a cooldown timer for python, basically just to print days,hours,minutes,seconds left from a certain date.
Thanks very much!
You can get the counter with the help of time delta function.
import datetime
import time
future_date = datetime.datetime.now()+ datetime.timedelta(seconds=3)
while True:
curr_date = datetime.datetime.now()
rem_time = future_date - curr_date
total_seconds = int(rem_time.total_seconds())
if total_seconds > 0:
days, h_remainder = divmod(total_seconds, 86400)
hours, remainder = divmod(h_remainder, 3600)
minutes, seconds = divmod(remainder, 60)
print("Time Left: {} days, {} hours, {} minutes, {} seconds".format(days, hours, minutes, seconds))
time.sleep(1)
else:
break
sample output will be:
Time Left: 0 days, 0 hours, 0 minutes, 2 seconds
Time Left: 0 days, 0 hours, 0 minutes, 1 seconds
Try this. The module datetime is preinstalled on Python, I believe.
import datetime
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
future = datetime.datetime(2022, 3, 31, 8, 0, 0)
difference = future - present
print(difference)
The format for datetime's future is: year, month, day, hour, minute, second.
Or, if you'd like to have user input:
import datetime
year = int(input('Enter the year of the end date: '))
month = int(input('Enter the month of the end date: '))
day = int(input('Enter the day of the end date: '))
hour = int(input('Enter the hour of the end date: '))
minute = int(input('Enter the minute of the end date: '))
second = int(input('Enter the second of the end date (a little tricky): '))
future = datetime.datetime(year, month, day, hour, minute, second)
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
difference = future - present
if present >= future:
break
print(difference)
print('Time reached!')
You can use the seconds from a timedelta from subtracting two dates to calculate the days, hours, minutes and seconds like this:
from datetime import datetime
import time
totalSecs = 1 #So the while loop doesn't stop immidiately
while totalSecs > 0:
startDate = datetime.now() #Can be any date
endDate = datetime(2021, 12, 25)
delta = endDate - startDate
totalSecs = delta.total_seconds()
days = divmod(totalSecs, 86400)
hrs = divmod(days[1], 3600)
mins = divmod(hrs[1], 60)
seconds = divmod(mins[1], 1)
print("{:02d}:{:02d}:{:02d}:{:02d}".format(int(days[0]), int(hrs[0]), int(mins[0]), int(seconds[0]))) #Zero pad all the numbers
time.sleep(1) #Print every second.
Thank you all for your replies, i've done a mistake when i made the post. Is not from a date. Is a countdown in day,hours,minutes,seconds from a certain amount of seconds. Let's say i've got 31104000 seconds and i want to print how many days,hours,minutes,seconds left from that amount of seconds.
The code i've got now is a bit trivial and i can't print seconds in realtime.
def SecondToDHM(time):
if time < 60:
return "%.2f %s" % (time, SECOND)
second = int(time % 60)
minute = int((time / 60) % 60)
hour = int((time / 60) / 60) % 24
day = int(int((time / 60) / 60) / 24)
text = ""
if day > 0:
text += str(day) + DAY
text += " "
if hour > 0:
text += str(hour) + HOUR
text += " "
if minute > 0:
text += str(minute) + MINUTE
text += " "
if second > 0:
text += str(second) + SECOND
return text
import datetime
a = datetime.datetime.now()
"%s:%s.%s" % (a.minute, a.second, str(a.microsecond))

Datetime: Check if date is in 1 week

What I am trying to do is see if date is in 1 week from currdate
from datetime import datetime, timedelta
import yagmail
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
currdate = '{}-{}-{}'.format(year, month, day)
currdate = datetime.strptime(currdate, '%Y-%m-%d')
date = '2018-04-01'
days = currdate - timedelta(int(date[-2:]))
days = str(days)
print(days)
if days[8:11] == '07':
yag = yagmail.SMTP("##########gmail.com", "######")
content = ['One Of Your Homework\'s Is Due In 1 Week!']
yag.send('###########gmail.com', 'Homework Due Soon!', content)
else:
print('It Isn\'t')
But it prints:
2018-04-07 00:00:00
It Isnt't
And I'm not sure why. Because days[8:11] is 07.
It is not 07. It's 07 (note the trailing space).
The following change will work:
if int(days[8:11]) == 7:
I'd create a function that you pass the date as a string. Something like this:
import datetime
def check_if_less_than_seven_days(x):
d = datetime.datetime.strptime(x, "%Y-%m-%d") # Add .date() if hour doesn't matter
now = datetime.datetime.now() # Add .date() if hour doesn't matter
return (d - now).days < 7
if check_if_less_than_seven_days("2018-04-18"):
print('Do something') # This will not print
if check_if_less_than_seven_days("2018-04-14"):
print('Do something') # This will print
Will print:
'Do something'
I suppose your first line when you initiate datetime.now() three times is just for testing purposes but dont do this as it could end up over different days (if you run this exactly at the milliseconds around midnight..) this will work better in that regard.
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
Anyway, read up on datetime timedelta. Just make you logic around that.
https://docs.python.org/3/library/datetime.html#timedelta-objects
import datetime
test_date_string = "2018-04-10"
d = datetime.datetime.strptime(test_date_string, "%Y-%m-%d")
now = datetime.datetime.now()
delta = d - now
elif delta.days < 7:
print("You have less then 7 days to go")
For days[8:11] you get the following output
>>> days[8:11]
'08 '
So you should use days[8:10]=='07' in case you want to use the same method,as it wont have extra space at the end.
>>> days[8:10]
'08'
so you should use
if days[8:10] == '07':

How could a datetime.timedelta object be manipulated to allow it to be styled and printed in a manner similar to that for a datetime.datetime object?

I have a function that can be used to print a datetime.datetime object in a specified style. I want to be able to print in similar styles the information contained in a datetime.timedelta object. How could the datetime.timedelta object be manipulated such that it can be styled easily, like by using the function that's already defined?
My code is below (and the answer should be around 82 days, 14 hours).
#!/usr/bin/env python
import datetime
def main():
print("current time UTC:\n")
print(
style_datetime_object(
datetime_object = datetime.datetime.utcnow(),
style = "HH hours MM minutes SS seconds day DD month YYYY"
)
)
year_ICHEP_2016 = 2016
month_ICHEP_2016 = 8
day_ICHEP_2016 = 3
datetime_object_ICHEP_2016_time = datetime.datetime(
year_ICHEP_2016,
month_ICHEP_2016,
day_ICHEP_2016
)
datetime_object_current_time_UTC = datetime.datetime.utcnow()
datetime_object_current_time_UTC_to_ICHEP_2016_time =\
datetime_object_ICHEP_2016_time - datetime_object_current_time_UTC
# insert magic to style datetime.timedelta
# `datetime_object_current_time_UTC_to_ICHEP_2016_time' using function
# `style_datetime_object`
#
# print(
# style_datetime_object(
# datetime_object = datetime_object_current_time_UTC_to_ICHEP_2016_time,
# style = "HH hours MM minutes SS seconds day DD month YYYY"
# )
# )
def style_datetime_object(
datetime_object = None,
style = "YYYY-MM-DDTHHMMZ"
):
# filename safe
if style == "YYYY-MM-DDTHHMMZ":
return datetime_object.strftime("%Y-%m-%dT%H%MZ")
# filename safe with seconds
elif style == "YYYY-MM-DDTHHMMSSZ":
return datetime_object.strftime("%Y-%m-%dT%H%M%SZ")
# filename safe with seconds and microseconds
elif style == "YYYY-MM-DDTHHMMSSMMMMMMZ":
return datetime_object.strftime("%Y-%m-%dT%H%M%S%fZ")
# elegant
elif style == "YYYY-MM-DD HH:MM:SS UTC":
return datetime_object.strftime("%Y-%m-%d %H:%M:%SZ")
# UNIX time in seconds with second fraction
elif style == "UNIX time S.SSSSSS":
return (datetime_object -\
datetime.datetime.utcfromtimestamp(0)).total_seconds()
# UNIX time in seconds rounded
elif style == "UNIX time S":
return int((datetime_object -\
datetime.datetime.utcfromtimestamp(0)).total_seconds())
# human-readable date
elif style == "day DD month YYYY":
return datetime_object.strftime("%A %d %B %Y")
# human-readable time and date
elif style == "HH:MM day DD month YYYY":
return datetime_object.strftime("%H:%M %A %d %B %Y")
# human-readable time with seconds and date
elif style == "HH:MM:SS day DD month YYYY":
return datetime_object.strftime("%H:%M:%S %A %d %B %Y")
# human-readable date with time with seconds
elif style == "day DD month YYYY HH:MM:SS":
return datetime_object.strftime("%A %d %B %Y %H:%M:%S")
# human-readable-audible time with seconds and date
elif style == "HH hours MM minutes SS seconds day DD month YYYY":
return datetime_object.strftime("%H hours %M minutes %S seconds %A %d %B %Y")
# human-readable days, hours and minutes
elif style == "DD:HH:MM":
return datetime_object.strftime("%d:%H:%M")
# human-readable days, hours, minutes and seconds
elif style == "DD:HH:MM:SS":
return datetime_object.strftime("%d:%H:%M:%S")
# human-readable time with seconds
elif style == "HH:MM:SS":
return datetime_object.strftime("%H:%M:%S")
# human-readable-audible time with seconds
elif style == "HH hours MM minutes SS seconds":
return datetime_object.strftime("%H hours %M minutes %S seconds")
# filename safe
else:
return datetime_object.strftime("%Y-%m-%dT%H%MZ")
if __name__ == '__main__':
main()

Python format timedelta greater than 24 hours for display only containing hours?

How do I format timedelta greater than 24 hours for display only containing hours in Python?
>>> import datetime
>>> td = datetime.timedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
'1 day, 12:10:10'
# my expected result is:
'36:10:10'
I acheive it by:
import datetime
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
>>> print(str)
36:10:10
Is there a better way?
May be defining your class that inherits datetime.timedelta will be a little more elegant
class mytimedelta(datetime.timedelta):
def __str__(self):
seconds = self.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
return (str)
td = mytimedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
prints '36:10:10'
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'
More info: http://babel.pocoo.org/docs/dates/
This will format your interval according to a given locale. I guess it is better, because it will always use the official format for your locale.
Oh, and it has a granularity parameter. (I hope I could understand your question...)

User-friendly time format in Python?

Python: I need to show file modification times in the "1 day ago", "two hours ago", format.
Is there something ready to do that? It should be in English.
The code was originally published on a blog post "Python Pretty Date function" (http://evaisse.com/post/93417709/python-pretty-date-function)
It is reproduced here as the blog account has been suspended and the page is no longer available.
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time, datetime):
diff = now - time
elif not time:
diff = 0
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff // 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff // 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff // 7) + " weeks ago"
if day_diff < 365:
return str(day_diff // 30) + " months ago"
return str(day_diff // 365) + " years ago"
If you happen to be using Django, then new in version 1.4 is the naturaltime template filter.
To use it, first add 'django.contrib.humanize' to your INSTALLED_APPS setting in settings.py, and {% load humanize %} into the template you're using the filter in.
Then, in your template, if you have a datetime variable my_date, you can print its distance from the present by using {{ my_date|naturaltime }}, which will be rendered as something like 4 minutes ago.
Other new things in Django 1.4.
Documentation for naturaltime and other filters in the django.contrib.humanize set.
In looking for the same thing with the additional requirement that it handle future dates, I found this:
http://pypi.python.org/pypi/py-pretty/1
Example code (from site):
from datetime import datetime, timedelta
now = datetime.now()
hrago = now - timedelta(hours=1)
yesterday = now - timedelta(days=1)
tomorrow = now + timedelta(days=1)
dayafter = now + timedelta(days=2)
import pretty
print pretty.date(now) # 'now'
print pretty.date(hrago) # 'an hour ago'
print pretty.date(hrago, short=True) # '1h ago'
print pretty.date(hrago, asdays=True) # 'today'
print pretty.date(yesterday, short=True) # 'yest'
print pretty.date(tomorrow) # 'tomorrow'
You can also do that with arrow package
From github page:
>>> import arrow
>>> utc = arrow.utcnow()
>>> utc = utc.shift(hours=-1)
>>> utc.humanize()
'an hour ago'
There is humanize package:
>>> from datetime import datetime, timedelta
>>> import humanize # $ pip install humanize
>>> humanize.naturaltime(datetime.now() - timedelta(days=1))
'a day ago'
>>> humanize.naturaltime(datetime.now() - timedelta(hours=2))
'2 hours ago'
It supports localization l10n, internationalization i18n:
>>> _ = humanize.i18n.activate('ru_RU')
>>> print humanize.naturaltime(datetime.now() - timedelta(days=1))
день назад
>>> print humanize.naturaltime(datetime.now() - timedelta(hours=2))
2 часа назад
The answer Jed Smith linked to is good, and I used it for a year or so, but I think it could be improved in a few ways:
It's nice to be able to define each time unit in terms of the preceding unit, instead of having "magic" constants like 3600, 86400, etc. sprinkled throughout the code.
After much use, I find I don't want to go to the next unit quite so eagerly. Example: both 7 days and 13 days will show as "1 week"; I'd rather see "7 days" or "13 days" instead.
Here's what I came up with:
def PrettyRelativeTime(time_diff_secs):
# Each tuple in the sequence gives the name of a unit, and the number of
# previous units which go into it.
weeks_per_month = 365.242 / 12 / 7
intervals = [('minute', 60), ('hour', 60), ('day', 24), ('week', 7),
('month', weeks_per_month), ('year', 12)]
unit, number = 'second', abs(time_diff_secs)
for new_unit, ratio in intervals:
new_number = float(number) / ratio
# If the new number is too small, don't go to the next unit.
if new_number < 2:
break
unit, number = new_unit, new_number
shown_num = int(number)
return '{} {}'.format(shown_num, unit + ('' if shown_num == 1 else 's'))
Notice how every tuple in intervals is easy to interpret and check: a 'minute' is 60 seconds; an 'hour' is 60 minutes; etc. The only fudge is setting weeks_per_month to its average value; given the application, that should be fine. (And note that it's clear at a glance that the last three constants multiply out to 365.242, the number of days per year.)
One downside to my function is that it doesn't do anything outside the "## units" pattern: "Yesterday", "just now", etc. are right out. Then again, the original poster didn't ask for these fancy terms, so I prefer my function for its succinctness and the readability of its numerical constants. :)
The ago package provides this. Call human on a datetime object to get a human readable description of the difference.
from ago import human
from datetime import datetime
from datetime import timedelta
ts = datetime.now() - timedelta(days=1, hours=5)
print(human(ts))
# 1 day, 5 hours ago
print(human(ts, precision=1))
# 1 day ago
Using datetime objects with tzinfo:
def time_elapsed(etime):
# need to add tzinfo to datetime.utcnow
now = datetime.utcnow().replace(tzinfo=etime.tzinfo)
opened_for = (now - etime).total_seconds()
names = ["seconds","minutes","hours","days","weeks","months"]
modulos = [ 1,60,3600,3600*24,3600*24*7,3660*24*30]
values = []
for m in modulos[::-1]:
values.append(int(opened_for / m))
opened_for -= values[-1]*m
pretty = []
for i,nm in enumerate(names[::-1]):
if values[i]!=0:
pretty.append("%i %s" % (values[i],nm))
return " ".join(pretty)
I have written a detailed blog post for the solution on http://sunilarora.org/17329071
I am posting a quick snippet here as well.
from datetime import datetime
from dateutil.relativedelta import relativedelta
def get_fancy_time(d, display_full_version = False):
"""Returns a user friendly date format
d: some datetime instace in the past
display_second_unit: True/False
"""
#some helpers lambda's
plural = lambda x: 's' if x > 1 else ''
singular = lambda x: x[:-1]
#convert pluran (years) --> to singular (year)
display_unit = lambda unit, name: '%s %s%s'%(unit, name, plural(unit)) if unit > 0 else ''
#time units we are interested in descending order of significance
tm_units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
rdelta = relativedelta(datetime.utcnow(), d) #capture the date difference
for idx, tm_unit in enumerate(tm_units):
first_unit_val = getattr(rdelta, tm_unit)
if first_unit_val > 0:
primary_unit = display_unit(first_unit_val, singular(tm_unit))
if display_full_version and idx < len(tm_units)-1:
next_unit = tm_units[idx + 1]
second_unit_val = getattr(rdelta, next_unit)
if second_unit_val > 0:
secondary_unit = display_unit(second_unit_val, singular(next_unit))
return primary_unit + ', ' + secondary_unit
return primary_unit
return None
DAY_INCREMENTS = [
[365, "year"],
[30, "month"],
[7, "week"],
[1, "day"],
]
SECOND_INCREMENTS = [
[3600, "hour"],
[60, "minute"],
[1, "second"],
]
def time_ago(dt):
diff = datetime.now() - dt # use timezone.now() or equivalent if `dt` is timezone aware
if diff.days < 0:
return "in the future?!?"
for increment, label in DAY_INCREMENTS:
if diff.days >= increment:
increment_diff = int(diff.days / increment)
return str(increment_diff) + " " + label + plural(increment_diff) + " ago"
for increment, label in SECOND_INCREMENTS:
if diff.seconds >= increment:
increment_diff = int(diff.seconds / increment)
return str(increment_diff) + " " + label + plural(increment_diff) + " ago"
return "just now"
def plural(num):
if num != 1:
return "s"
return ""
This is the gist of #sunil 's post
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> then = datetime(2003, 9, 17, 20, 54, 47, 282310)
>>> relativedelta(then, datetime.now())
relativedelta(years=-11, months=-3, days=-9, hours=-18, minutes=-17, seconds=-8, microseconds=+912664)
You can download and install from below link. It should be more helpful for you. It has been providing user friendly message from second to year.
It's well tested.
https://github.com/nareshchaudhary37/timestamp_content
Below steps to install into your virtual env.
git clone https://github.com/nareshchaudhary37/timestamp_content
cd timestamp-content
python setup.py
Here is an updated answer based on Jed Smith's implementation that properly hands both offset-naive and offset-aware datetimes. You can also give a default timezones. Python 3.5+.
import datetime
def pretty_date(time=None, default_timezone=datetime.timezone.utc):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
# Assumes all timezone naive dates are UTC
if time.tzinfo is None or time.tzinfo.utcoffset(time) is None:
if default_timezone:
time = time.replace(tzinfo=default_timezone)
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time, datetime.datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff / 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff / 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff / 7) + " weeks ago"
if day_diff < 365:
return str(day_diff / 30) + " months ago"
return str(day_diff / 365) + " years ago"
I've been dragging and tweaking this code from programming language to programming language for so long, I don't remember where I originally got it from. It served me well in PHP, Java, and TypeScript, and now it's time for Python.
It handles past and future dates, as well as edge cases.
def unix_time() -> int:
return int(time.time())
def pretty_time(t: int, absolute=False) -> str:
if not type(t) is int:
return "N/A"
if t == 0:
return "Never"
now = unix_time()
if t == now:
return "Now"
periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"]
lengths = [60, 60, 24, 7, 4.35, 12, 10]
diff = now - t
if absolute:
suffix = ""
else:
if diff >= 0:
suffix = "ago"
else:
diff *= -1
suffix = "remaining"
i = 0
while diff >= lengths[i] and i < len(lengths) - 1:
diff /= lengths[i]
i += 1
diff = round(diff)
if diff > 1:
periods[i] += "s"
return "{0} {1} {2}".format(diff, periods[i], suffix)
def time_ago(self):
start_time = self.date # The start date
now_time = datetime.now()
difference = int((now_time - start_time).total_seconds())
second = [1, 'seconds']
minute = [60, 'minutes']
hour = [60 * minute[0], 'hours']
day = [24 * hour[0], 'days']
week = [7 * day[0], 'weeks']
month = [4 * week[0], 'months']
year = [12 * month[0], 'years']
times = [year, month, week, day, hour, minute, second]
for time in times:
if difference >= time[0]:
time_ago = int(difference / time[0])
if time_ago <= 1:
timeframe = time[1].rstrip('s')
else:
timeframe = time[1]
time_item = str(time_ago) + ' ' + timeframe
return time_item
return 'Date Error'

Categories

Resources