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 h
Since Python 3.2, datetime.strptime()
returns an aware datetime object if %z
directive is provided:
#!/usr/bin/env python3
from datetime import datetime, timezone, timedelta
s = "Mon, 17 Nov 2008 01:45:32 +0200"
birthday = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
age = (datetime.now(timezone.utc) - birthday) / timedelta(1) # age in days
print("%.0f" % age)
On older Python versions the correct version of @Tony Meyer's answer could be used:
#!/usr/bin/env python
import time
from email.utils import parsedate_tz, mktime_tz
s = "Mon, 17 Nov 2008 01:45:32 +0200"
ts = mktime_tz(parsedate_tz(s)) # seconds since Epoch
age = (time.time() - ts) / 86400 # age in days
print("%.0f" % age)
Both code examples produce the same result.