Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic difference between two dates in years?

Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.

from datetime import datetime start_date = datetime(2010,4,28,12,33) end_date = datetime(2010,5,5,23,14) difference  = end_date - start_date difference_in_years = (difference.days + difference.seconds/86400)/365.2425 
like image 426
c00kiemonster Avatar asked Dec 14 '10 07:12

c00kiemonster


People also ask

How do I get the year difference between two dates in python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.

How do I calculate the difference between two dates in pandas?

Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.


1 Answers

If you want precise results, I recommend using the dateutil library.

from dateutil.relativedelta import relativedelta difference_in_years = relativedelta(end_date, start_date).years 

This is for complete years (e.g. a person's age). If you want fractional years, then add months, days, hours, ... up to the desired precision.

like image 104
Karl Bartel Avatar answered Oct 18 '22 08:10

Karl Bartel