[python] Calculation of months and years of difference in datetime

Motivated

When I add or subtract the datetime type, the timedelta type is returned, but it has only finer attributes than the day, and I always googled when calculating the month and year. So I will summarize it.

code

-Generate a new date by adjusting the date and the number of months (use relativedelta * timedelta cannot handle months) -Calculate the number of months and years of the difference between two dates (use monthmod)

#Create start date and time with datetime type-----------
from datetime import datetime
dt1 = datetime(2018,5,6)  # datetime.datetime(2018, 5, 6, 0, 0)

#Generate a new date by adding any number of months and days to the start date and time-----------
from dateutil.relativedelta import relativedelta
dt2 = start + relativedelta(months=20, days=25)  # datetime.datetime(2020, 1, 31, 0, 0)

#Find the difference between two dates on a daily basis-----------
dt_dif = (dt2 - dt1)  # datetime.timedelta(days=635)
print(dt_dif.days)  # 635
# print(dt_dif.months)  #Will be an error

#The difference between the two dates, on a monthly basis/Calculate on a yearly basis-----------
from monthdelta import monthmod  #If you get an error pip install MonthDelta
mmod = monthmod(dt1, dt2)  # (monthdelta(20), datetime.timedelta(days=25)) <-Tuple (like a list)

##Month difference (round off the remainder)
print(mmod[0].months)  # 20

##Year difference (round off the remainder) Divide the month difference by 12. There are various days in the month, but since the number of months in the year is always 12, this is ok
print(mmod[0].months//12)  # 1

reference

https://pythonhosted.org/MonthDelta/

Recommended Posts

[python] Calculation of months and years of difference in datetime
Dealing with "years and months" in Python
Calculation of elapsed years and elapsed months including leap years
Calculation of standard deviation and correlation coefficient in Python
Difference between Ruby and Python in terms of variables
Summary of date processing in Python (datetime and dateutil)
Difference between list () and [] in Python
Conversion of string <-> date (date, datetime) in Python
difference between statements (statements) and expressions (expressions) in Python
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Project Euler # 1 "Multiples of 3 and 5" in Python
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
Project Euler # 6 "Difference in sum of squares" in Python
Explanation of edit distance and implementation in Python
[Python] Class type and usage of datetime module
Date calculation in python
Date calculation in Python
"Linear regression" and "Probabilistic version of linear regression" in Python "Bayesian linear regression"
Experience the good calculation efficiency of vectorization in Python
Full-width and half-width processing of CSV data in Python
[Tips] First-order difference calculation and inverse conversion [python / numpy]
Difference between return, return None, and no return description in Python
Start numerical calculation in Python (with Homebrew and pip)
Overview of generalized linear models and implementation in Python
Sample of getting module name and class name in Python
[Python] Types of statistical values (features) and calculation methods
[Python] Explain the difference between strftime and strptime in the datetime module with an example
Find the difference in Python
Shapley value calculation in Python
Equivalence of objects in Python
About Python datetime and timezone
Stack and Queue in Python
Unittest and CI in Python
Implementation of quicksort in Python
Source installation and installation of Python
[Python] Heron's formula functionalization and calculation of the maximum area
Python module num2words Difference in behavior between English and Russian
Applied practice of try/except and dictionary editing and retrieval in Python
List concatenation method in python, difference between list.extend () and “+” operator
Reference order of class variables and instance variables in "self. Class variables" in Python
Comparison of how to use higher-order functions in Python 2 and 3
Get the current date and time in Python, considering the time difference
[Python] Strengths and weaknesses of DataFrame in terms of time required
[Tips] Problems and solutions in the development of python + kivy
Environment construction of python and opencv
Difference between Ruby and Python split
Pixel manipulation of images in Python
Difference between java and python (memo)
MIDI packages in Python midi and pretty_midi
Count the number of Thai and Arabic characters well in Python
View photos in Python and html
Quantum chemistry calculation in Python (Psi4)
Sorting algorithm and implementation in Python
Difference in behavior of transparent Frame made with tkinter in pyinstaller [Python]
Division of timedelta in Python 2.7 series
Manipulate files and folders in Python
MySQL-automatic escape of parameters in python
About dtypes in Python and Cython