I was searching for a way to find the difference between two timestamps. My requirement is to get the difference in terms of years, months, days, hours and minutes. I found a way to get it. The below code contains the logic to get the required output. I haven’t seen this code anywhere in internet, that is the reason I am posting this here so that this will be helpful for someone.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|__author__ = 'Amal G Jose'|
|from datetime import datetime|
|from dateutil import relativedelta|
|##Aug 7 1989 8:10 pm|
|date_1 = datetime(1989, 8, 7, 20, 10)|
|##Dec 5 1990 5:20 am|
|date_2 = datetime(1990, 12, 5, 5, 20)|
|#This will find the difference between the two dates|
|difference = relativedelta.relativedelta(date_2, date_1)|
|years = difference.years|
|months = difference.months|
|days = difference.days|
|hours = difference.hours|
|minutes = difference.minutes|
|print "Difference is %s year, %s months, %s days, %s hours, %s minutes " %(years, months, days, hours, minutes)|
Thanks I be searching for a way to do this. Your method is perfect.
he forgot brackets after the “print” function at the very end :3
otherwise it works fine
This was developed for Python version 2.7. The brackets were not required in 2.7. Now with Python 3, we need the brackets.