Rio
Rio

Reputation: 14892

Reverse pretty date format

Is there a way to go from

"1 day ago", "1 week ago", "3 hours ago"

to some date format like "Tue, 19 Jul 2011 10:00:00" using Python?

Upvotes: 2

Views: 403

Answers (3)

PaulMcG
PaulMcG

Reputation: 63749

This example on the pyparsing wiki supports these cases:

today
tomorrow
yesterday
in a couple of days
a couple of days from now
a couple of days from today
in a day
3 days ago
3 days from now
a day ago
in 2 weeks
in 3 days at 5pm
now
10 minutes ago
10 minutes from now
in 10 minutes
in a minute
in a couple of minutes
20 seconds ago
in 30 seconds
20 seconds before noon
20 seconds before noon tomorrow
noon
midnight
noon tomorrow
6am tomorrow
0800 yesterday
12:15 AM today
3pm 2 days from today
a week from today
a week from now
3 weeks ago
noon next Sunday
noon Sunday
noon last Sunday
2pm next Sunday
next Sunday at 2pm

Upvotes: 1

Escualo
Escualo

Reputation: 42132

I don't know whether there are libraries available (if there are, I'm sure they can be found in Django source code - it sounds like the kind of problems they must have thought of).

However, I don't find the problem too difficult in principle. You first define your boundaries. For example:

  • If it happened within one day, I'll spell out the hour
  • If it happened within six days, I'll spell out the number of days
  • If it happened within four weeks, I'll spell out the number of weeks
  • [etc]

Then you use the datetime module (specifically the timedelta object) and filter out your desires according to the duration. A basic version should be up an running in less than an hour.

Again - I encourage you to look for implemented solutions, but if you cannot figure out a basic way to get this working, I'm afraid your Python skills may be lacking and you may want to practice by reinventing the wheel.

Upvotes: 0

philnash
philnash

Reputation: 73055

The answer to this question suggests http://code.google.com/p/parsedatetime/

Upvotes: 4

Related Questions