4

I want to format a python timedelta object as "x minutes/hours/weeks/month/years ago".

I know there are some similar questions, like:

However, I did not find an answer for my case, because

  • I do not use django
  • I need to format a timedelta to a string, not the other way around
  • The solution should work in as many languages as possible, not just English

Here is my current code (excerpt, sorry):

delta = babel.dates.format_timedelta(now - dt, format=format,          
                                     locale=locale)                       
if now > dt:                                                           
    return _(u"%(timedelta)s ago") % {'timedelta': delta}              
else:                                                                  
    return _(u"in %(timedelta)s") % {'timedelta': delta} 

For the babel function, see http://babel.pocoo.org/docs/dates/#time-delta-formatting

Now this works fine in English. In German, however, it fails: The above code would translate "2 years ago" to "vor 2 Jahre" instead of "vor 2 Jahren".

I would also be happy with a solution that does not use the "... ago" phrasing. As long as it is similar and translatable I can accept it.

Community
  • 1
  • 1
tobib
  • 2,114
  • 4
  • 21
  • 35
  • Requests for libraries etc are off-topic here, but you could look into [Arrow](http://crsmithdev.com/arrow/) – jonrsharpe Jan 30 '14 at 16:32

3 Answers3

3

Here's a quick example that should put you on the right track:

>>> import datetime
>>> delta = datetime.timedelta(days=2)
>>> delta.days
2
>>> print delta
2 days, 0:00:00

You should create your formatting as it makes sense, perhaps someone else can put you on to an answer out of the box here.

>>> '{0} ago'.format(delta)
'2 days, 0:00:00 ago'

A function for the timedelta object

def total_hours(a_timedelta):
    return a_timedelta.total_seconds()/60.0/60.0

Usage:

>>> total_hours(delta)
48.0
>>> '{0} hours ago'.format(total_hours(delta))
'48.0 hours ago'
>>> then = datetime.datetime.now() 
>>> diff = datetime.datetime.now() - then
>>> diff
datetime.timedelta(0, 12, 967773)
>>> '{0} hours ago'.format(total_hours(diff))
'0.00360215916667 hours ago'
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
3

According to documentation I found here, you should add the add_direction=True parameter to your format_timedelta call.

Sascha Gottfried
  • 3,303
  • 20
  • 30
kemitche
  • 791
  • 3
  • 15
2

You may want to use the arrow package, especially the humanize function :

import arrow
a = arrow.now()
print a.humanize()

Output : "just now"

For your needs, suppose you have a date like:

myDate = "2019-02-10 08:00:00"
a = arrow.get(myDate, "YYYY-DD-MM HH:mm:ss")
print a.humanize()

Output : "an hour ago"

You can find the doc here : https://arrow.readthedocs.io/en/latest/