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
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.
Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With