Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find time until a date in Python

Tags:

python

What's the best way to find the time until a date. I would like to know the years, months, days and hours.

I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.

like image 759
Joe Avatar asked Dec 03 '22 07:12

Joe


2 Answers

datetime module, datetime and timedelta objects, it will give you days and seconds.

In [5]: datetime.datetime(2009, 10, 19) - datetime.datetime.now()
Out[5]: datetime.timedelta(2, 5274, 16000)

In [6]: td = datetime.datetime(2009, 10, 19) - datetime.datetime.now()

In [7]: td.days
Out[7]: 2

In [8]: td.seconds
Out[8]: 5262
like image 181
Cat Plus Plus Avatar answered Dec 14 '22 23:12

Cat Plus Plus


You should use dateutil.relativedelta.

from dateutil.relativedelta import relativedelta
import datetime
today = datetime.date.today()
rd = relativedelta(today, datetime.date(2001,1,1))
print "comment created %(years)d years, %(months)d months, %(days)d days ago" % rd.__dict__
like image 44
Jason R. Coombs Avatar answered Dec 15 '22 01:12

Jason R. Coombs