Get last month in python

Like 201612, I wanted to take the value of last month regardless of the date, so I wrote the code.

#Library import
import datetime

#Get today
today = datetime.datetime.today()
print today.strftime("%Y-%m-%d")

#Get the value for the first day of the month
thismonth = datetime.datetime(today.year, today.month, 1)
print thismonth.strftime("%Y-%m-%d")

#Get the value for the last day of the previous month
lastmonth = thismonth + datetime.timedelta(days=-1)
print lastmonth

#Specify the format and pick up only the year and month
print lastmonth.strftime("%Y%m")

It's a bit of a hassle, but I wanted to do it with just the default libraries that AWS Lambda can use.

Recommended Posts

Get last month in python
Get date in Python
Get YouTube Comments in Python
Get Terminal size in Python
[Python] Get the previous month
Explicitly get EOF in python
Get Evernote notes in Python
Get Japanese synonyms in Python
Get Leap Motion data in Python.
Get data from Quandl in Python
Get the desktop path in Python
Get the script path in Python
Get, post communication memo in Python
Calculate the previous month in Python
Get the desktop path in Python
Get the host name in Python
Python Note: Get the current month
Get started with Python in Blender
How to get the last (last) value in a list in Python
Get additional data in LDAP with python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
SendKeys in Python
Get exchange rates from open exchange rates in Python
Get Suica balance in Python (using libpafe)
Meta-analysis in Python
Unittest in python
[Python] How to get the first and last days of the month
Epoch in Python
Discord in Python
Get Google Fit API data in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
How to get a stacktrace in python
Programming in python
Get Youtube data in Python using Youtube Data API
Plink in Python
Constant in python
Get battery level from SwitchBot in Python
Get a token for conoha in python
Get Started with TopCoder in Python (2020 Edition)
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Get the last day of the specified month
Constant in python
nCr in Python.
format in python
Scons in Python3