2

Does anyone know of a Python module that will convert an RFC 822 timestamp into a human readable format (like Twitter does) in Python?

I found parsedatetime, which seems to do the reverse.

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
Sean W.
  • 4,944
  • 8
  • 40
  • 66

3 Answers3

8

In python, you can use rfc822 module. This module provides the parsedate method.

Attempts to parse a date according to the rules in RFC 2822.

However, this module is deprecated.

Deprecated since version 2.3: The email package should be used in preference to the rfc822 module. This module is present only to maintain backward compatibility, and has been removed in 3.0.

According to this comment, it's better to use the parsedate method from the email.utils module.

email.utils.parsedate(date)

EDIT:

Example code :

import email.utils
from time import mktime
from datetime import datetime

example_date = "Sat, 02 Mar 2011 15:00:00"
date_parsed = email.utils.parsedate(example_date)
dt = datetime.fromtimestamp(mktime(date_parsed))

today = datetime.today()
diff_date = today - dt  # timedelta object

print "%s days, %s hours ago" \
    % (diff_date.days, diff_date.seconds / 3600)

Output (for now) :

31 days, 2 hours ago
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • Hi, do you know of a way to convert the output of parsedate to a "human readable" format, similar to the way twitter does? For example, two hours ago. – Sean W. Apr 02 '11 at 14:52
  • 1
    I just noticed that the above example assumes the original format is in GMT. Can you correct it so that it accounts for timezones? I tried to replace parsedate with parsedate_tz, but that did not work. Thanks again. – Sean W. Apr 03 '11 at 00:34
2

datetime.strptime will turn the times stamp into a datetime object which you can format with datetime.strftime

http://docs.python.org/library/datetime.html#strftime-strptime-behavior

Mike Ramirez
  • 10,750
  • 3
  • 26
  • 20