User-friendly time format in Python?

python datetime format
strptime python
astimezone python
python isodate
python utc timestamp
python datetime timezone
python 3 datetime now
days 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 = 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"

WorkingWithTime, format. Python. seconds since the "Epoch". time.time(). tuple. time.gmtime() compare these usefully, but they're what you need to display things to the user. Format the current time in Python Once we have a time.struct_time object, we can format it into a string so that it can be further processed by another program. We can do so by calling time.strftime (format [, t]) with the current time object as the argument t.

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.

8.1. datetime — Basic date and time types, For applications requiring aware objects, datetime and time objects have an optional This makes it possible to specify format string for a date object when using tzinfo methods can rely on this, unless user code calls tzinfo methods directly. time. strftime (format[, t]) ¶ Convert a tuple or struct_time representing a time as returned by gmtime () or localtime () to a string as specified by the format argument. If t is not provided, the current time as returned by localtime () is used. format must be a string. ValueError is raised if any field in t is outside of the allowed range.

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'

time — Time access and conversions, Function strptime() can parse 2-digit years when given %y format code. seconds) of the sum of the system and user CPU time of the current process. It is an object with a named tuple interface: values can be accessed by index and by  The strptime method does the opposite, that is, it takes strings and converts them into date objects that Python can understand. Here is the syntax for the method: datetime.strptime (string, format) The string parameter is the value in string format that we want to convert into date format.

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'

Arrow: Better dates & times for Python, Returns an ISO 8601 formatted representation of the date and time. Usage: >>> arrow.utcnow().isoformat  Let’s add a bare-bones Python timer to the example with time.perf_counter (). Again, this is a performance counter that’s well-suited for timing parts of your code. perf_counter () measures the time in seconds from some unspecified moment in time, which means that the return value of a single call to the function isn’t useful.

Using Python datetime to Work With Dates and Times – Real Python, The advantage of this format is that the date can be represented with no If the time zone rules for your user's location change before the future date datetime provides three classes that make up the high-level interface that  Pythom time method strftime () converts a tuple or struct_time representing a time as returned by gmtime () or localtime () to a string as specified by the format argument. If t is not provided, the current time as returned by localtime () is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range.

A Beginner's Guide to the Python time Module – Real Python, In this tutorial, you'll learn how to use the Python time module to represent dates the tuple provides a more readable interface for working with time components. may want to format your strings in a way that's more meaningful to your users. How to display "x days ago" type time using Humanize in Django template? From: "1 hour ago", To: timedelta + accuracy; User-friendly time format in Python? 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

Formatting Dates and Times, For displaying a time with a user friendly time zone name. zzzz, Long specific non​-location format (e.g. “Pacific Standard  time.strftime (format) ¶ Return a string representing the time, controlled by an explicit format string. For a complete list of formatting directives, see section strftime() and strptime() Behavior. time.__format__ (format) ¶ Same as time.strftime(). This makes it possible to specify a format string for a time object when using str.format().

Date and Time, When working with date and time information in Python, you commonly use the Babel provides functions for locale-specific formatting of those objects in its use UTC internally and only reformat to local time when returning dates to users. The module is generally wrapped for you so you can directly interface with it from​  Multiple pairs of curly braces can be used while formatting the string. Let’s say if another variable substitution is needed in sentence, can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders by values in order. Syntax : { } { } .format(value1, value2) Parameters :

Comments
  • that is tailored to my exact needs. Thanks!
  • The link no longer exists and is giving a Forbidden. Need a permlink here or the content to be moved into this post.
  • @Chris: Thanks for the heads up, and it was still in Google Cache so I snagged it.
  • This does not work for me. I get this error: local variable 'diff' referenced before assignment why?
  • I threw this up to the cheeseshop: (pypi.python.org/pypi/human_dates/0.1.0) and github.com/jtushman/human_dates
  • Is adding it to INSTALLED_APPS really necessary? It worked without that for me, although I used the filter inside python, not the template
  • Can I use this inside view
  • Unfortunately py-pretty does not seem to allow i18n.
  • Nice solution. Keeping it simple allows more reuse. E.g can use suffix for relative time value + " ago" or duration value + " left"
  • Note that humanize does not support timezone-aware datetimes; you’ll have to convert those via into naive ones (in the local timezone) with dt.astimezone().replace(tzinfo=None).