Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

datetime - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...