2

I'd like to make my code a little more user-friendly such that when users post something, i'd like it to say "x seconds/hour/day ago"

so far my code is

{{ post.date_posted.strftime('%Y-%m-%d %H:%M:%S') }}

1 Answers1

1

You want datetime.timedelta()

import datetime
import time

old_time = datetime.datetime.now()
time.sleep(20)
new_time = datetime.datetime.now()

# The below line returns a 'timedelta' object.
delta = new_time - old_time

print('{} seconds have passed.'.format(delta.total_seconds()))

# or
print(
    '{} days, {} hours, {} minutes, {} seconds passed.'.format(
        delta.days,
        delta.seconds//3600,
        (delta.seconds//60)%60,
        int(delta.total_seconds()%60)))

I believe it also exists for just date and time modules as well.

UtahJarhead
  • 2,091
  • 1
  • 14
  • 21
  • While this works, it is typically not very nice to format the passed time in seconds only. To get minutes and hours, a custom filter is needed, to check and transform the `timedela` object to a nice looking string. – JohanL Oct 06 '18 at 07:19
  • Added that, too. – UtahJarhead Oct 06 '18 at 07:40
  • 1
    I think it's worth checking out the rather elegant solution over [here](https://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects) for a very `strftime`-like option. – UtahJarhead Oct 06 '18 at 07:50