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
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.
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.
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.
require 'Date'
puts Date.new(2001,2,-1).day
Uo, one line ...
output
28
I feel like it's Ruby-like.
end.
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