views:

1100

answers:

5
+2  Q: 

Python time to age

I'm trying to convert a date string into an age.

The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.

I have sucessfully converted the date using:

>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)

For some reason %z gives me an error for the +0200 but it doesn't matter that much.

I can get the current time using:

>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)

but how can I subtract one from the other without going though each item in the list and doing it manually?

+15  A: 

You need to use the module datetime and the object datetime.timedelta

from datetime import datetime

t1 = datetime.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
t2 = datetime.now()

tdelta = t2 - t1 # actually a datetime.timedelta object
print tdelta.days
Georg
The code snippet is incorrect. You need to import 'datetime' from datetime, not date (or use the date object, rather than the datetime object).
Tony Meyer
+2  A: 
from datetime import datetime, timedelta
datetime.now()
datetime.datetime(2009, 2, 3, 15, 17, 35, 156000)
datetime.now() - datetime(1984, 6, 29 )
datetime.timedelta(8985, 55091, 206000)
datetime.now() - datetime(1984, 6, 29 )
datetime.timedelta(8985, 55094, 198000) # my age...

timedelta(days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

Alex. S.
+4  A: 

In Python, datetime objects natively support subtraction:

from datetime import datetime
age = datetime.now() - datetime.strptime(...)
print age.days

The result is a timedelta object.

Ben Blank
A: 

Thanks guys, I ended up with the following:

def getAge( d ):
    """ Calculate age from date """
    delta = datetime.now() - datetime.strptime(d, "%a, %d %b %Y %H:%M:%S +0200")
    return delta.days + delta.seconds / 86400.0 # divide secs into days

Giving:

>>> getAge("Mon, 17 Nov 2008 01:45:32 +0200")
78.801319444444445
Ashy
That isn't guaranteed to be correct because of leap years (and seconds).
Georg
The datetime module knows about leap years. It may well also know about leap seconds also, but that hardly seems relevant when the OP is concerned about time in days.
Tony Meyer
It looks like he's concerned about time in years.
Georg
The function returns number of days.Its not vital that it is super accurate for what I need.Thanks! :)
Ashy
A: 

If you don't want to use datetime (e.g. if your Python is old and you don't have the module), you can just use the time module.

s = "Mon, 17 Nov 2008 01:45:32 +0200"
import time
import email.utils # Using email.utils means we can handle the timezone.
t = email.utils.parsedate_tz(s) # Gets the time.mktime 9-tuple, plus tz
d = time.time() - time.mktime(t[:9]) + t[9] # Gives the difference in seconds.
Tony Meyer