Calculate the previous month in Python

It was unexpectedly annoying, so make a note of it. Use a third-party module called python-dateutil. I thought it could be calculated with datetime.timedelta, but it didn't seem to support the calculation of the month.

pip install python-dateutil
from datetime import datetime, date, timedelta

from dateutil.relativedelta import relativedelta


today = datetime.today()
previous_month = today - relativedelta(months=1)
print(previous_month.month)
12

Recommended Posts

Calculate the previous month in Python
[Python] Get the previous month
Calculate mW <-> dBm in Python
Get last month in python
Download the file in Python
Find the difference in Python
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Calculate the square root of 2 in millions of digits with python
Get the desktop path in Python
Calculate free-space path loss in Python
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
Try to calculate Trace in Python
Hit the web API in Python
I wrote the queue in Python
Examine the object's class in python
Get the desktop path in Python
Get the host name in Python
Access the Twitter API in Python
Python Note: Get the current month
The first step in Python Matplotlib
I wrote the stack in Python
Master the weakref module in Python
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Try using the Wunderlist API in Python
Check the behavior of destructor in Python
Learn the design pattern "Flyweight" in Python
Try using the Kraken API in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Write the test in a python docstring
Learn the design pattern "Command" in Python
OR the List in Python (zip function)
Display Python 3 in the browser with MAMP
Tweet using the Twitter API in Python
Learn the design pattern "Bridge" in Python
Check if the URL exists in Python
Learn the design pattern "Mediator" in Python
Associate the table set in python models.py
The result of installing python in Anaconda
What is "mahjong" in the Python library? ??
Read the file line by line in Python
Read the file line by line in Python
MongoDB for the first time in Python
Learn the design pattern "Iterator" in Python
The basics of running NoxPlayer in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Solve the maximum subarray problem in Python
In search of the fastest FizzBuzz in Python
Learn the design pattern "State" in Python
Try hitting the YouTube API in Python
Get the EDINET code list in Python
Learn the design pattern "Adapter" in Python
When the previous graph remains in Seaborn
Install the Python module in any directory