Note: How to get the last day of the month with python (added the first day of the month)

Acquisition of the "end of the month" of a certain date-related program. After all, it's just as a reference for StackOverflow ... Note.

date - Get Last Day of the Month in Python - Stack Overflow

Caution

There is python, but do not create a program file with a name such as calendar.py. Because it will be called instead of the standard module. if

AttributeError: 'module' object has no attribute 'Calendar'

And,

AttributeError: 'module' object has no attribute 'monthrange'

If you get an error like that, delete the calendar.pyc that should have been generated in your working directory.

How to use the calendar module

For example, in December 2014.

import calendar

print calendar.monthrange(2014,12)

According to 8.2. calendar — general calendar functions — Python 2.7ja1 documentation

calendar.monthrange (year, month) Returns the day of the week and the number of days in the month specified by year and month.

so,

output


(0, 31)

Will be returned. This means that the first day of the month is Monday (day number 0) and the number of days in the specified month is 31 days.

So

import calendar

_, lastday = calendar.monthrange(2014,12)
print(lastday)

output


31

The result is the last day of the designated month.

How to use datetime.timedelta (days = 1)

Subtract one day from the beginning of the following month. In the datetime module, addition / subtraction and magnitude comparison can be performed using arithmetic operators by using the timedelta subclass.

8.1. datetime — basic date and time types — Python 2.7ja1 documentation

import datetime

date = datetime.date(2015, 1, 1) - datetime.timedelta(days=1)
print date.day

output


31

I feel that either of the above methods is good.

I think the first day of the month will be required as follows.

import datetime

dt = datetime.datetime.utcnow()
# datetime.datetime(2017, 11, 26, 20, 51, 59, 745695)
dt.date() - datetime.timedelta(days=dt.day - 1)
# datetime.date(2017, 11, 1)

that's all.

By the way, Ruby

require 'Date'
puts Date.new(2001,2,-1).day

Uo, one line ...

output


28

I feel like it's Ruby-like.

end.


Postscript

Last day of the previous month

from datetime import datetime, timedelta

yesterday = datetime(2018, 3, 29).date()
last_day_of_previous_month = yesterday - timedelta(days=yesterday.day)

Recommended Posts

Note: How to get the last day of the month with python (added the first day of the month)
[Python] How to get the first and last days of the month
Get the last day of the specified month
Note: Get the first and last items of Python OrderedDict non-destructively
How to get the number of digits in Python
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
How to get the Python version
How to get started with Python
Python Note: Get the current month
How to get the last (last) value in a list in Python
How to get into the python development environment with Vagrant
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)
PhytoMine-I tried to get the genetic information of plants with Python
How to get the date and time difference in seconds with python
I tried to get the authentication code of Qiita API with Python.
I tried to get the movie information of TMDb API with Python
[Note] Export the html of the site with python.
How to specify attributes with Mock of python
[Python] Get the last updated date of the website
How to get dictionary type elements of Python 2.7
How to get the files in the [Python] folder
[Python] Get the day of the week (English & Japanese)
[Python] How to compare datetime with timezone added
Python script to get note information with REAPER
[Python] How to make the file name of the output data unique (use year, month, day, hour, second)
How to get started with the 2020 Python project (windows wsl and mac standardization)
How to get the variable name itself in python
[Introduction to Python] How to iterate with the range function?
The first algorithm to learn with Python: FizzBuzz problem
[Python] How to specify the download location with youtube-dl
Try to get the contents of Word with Golang
How to get mouse wheel verdict with Python curses
[Python] Summary of how to specify the color of the figure
[Python] How to rewrite the table style with python-pptx [python-pptx]
Get the operation status of JR West with Python
Python Note: The mystery of assigning a variable to a variable
Get last month in python
The first step of machine learning ~ For those who want to implement with python ~
How to identify the element with the smallest number of characters in a Python list?
How to get started with Visual Studio Online ~ The end of the environment construction era ~
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
[Python] Get the previous month
[Note] How to write QR code and description in the same image with python
How to count the number of occurrences of each element in the list in Python with weight
The 15th offline real-time I tried to solve the problem of how to write with python
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
Try to get the function list of Python> os package
How to test the attributes added by add_request_method of pyramid
The first API to make with python Djnago REST framework
Minimum knowledge to get started with the Python logging module
(Note) How to pass the path of your own module
How to get a list of built-in exceptions in python
[Python] The first step to making a game with Pyxel
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
How to write offline real time I tried to solve the problem of F02 with Python