高校物理160203 views
高校国語788336 views
高校化学2924392 views
雑学1473612 views
高校日本史190571 views
小学社会310485 views
英語613639 views
小学算数1200427 views
りんご209490 views
高校生物551766 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Python で月初・月末・週初めの日付を取得する

レポート作成や集計処理では、月初・月末・週初めといった区切りの日付が必要になります。Python でこれらを取得する方法をまとめました。

月初を取得する

replace() メソッドで日を 1 に置き換えるだけです。

from datetime import date

today = date(2025, 1, 15)
first_day = today.replace(day=1)

print(first_day)  # 2025-01-01

datetime オブジェクトでも同様に使えます。時刻部分はそのまま維持されます。

from datetime import datetime

now = datetime(2025, 1, 15, 14, 30, 0)
first_day = now.replace(day=1)

print(first_day)  # 2025-01-01 14:30:00

月末を取得する

月末は月によって日数が異なるため、calendar.monthrange() を使います。

from datetime import date
import calendar

today = date(2025, 1, 15)
last_day_num = calendar.monthrange(today.year, today.month)[1]
last_day = today.replace(day=last_day_num)

print(last_day)  # 2025-01-31

monthrange()(月の最初の曜日, 月の日数) のタプルを返します。2番目の要素が月末の日付です。2月のうるう年も自動で考慮されます。

import calendar

# 2024年はうるう年
print(calendar.monthrange(2024, 2))  # (3, 29)

# 2025年は平年
print(calendar.monthrange(2025, 2))  # (5, 28)

週初め(月曜日)を取得する

weekday() メソッドを使って、当日からの差分を計算します。

from datetime import date, timedelta

today = date(2025, 1, 15)  # 水曜日
monday = today - timedelta(days=today.weekday())

print(monday)  # 2025-01-13

weekday() は月曜が 0、火曜が 1、…、日曜が 6 を返すため、その値を引けば月曜日になります。

週末(日曜日)を取得する

月曜日から6日足せば日曜日です。

from datetime import date, timedelta

today = date(2025, 1, 15)
monday = today - timedelta(days=today.weekday())
sunday = monday + timedelta(days=6)

print(sunday)  # 2025-01-19

翌月・前月の初日を取得する

月をまたぐ計算は少し工夫が必要です。

from datetime import date

def next_month_first(d):
    """翌月の1日を取得"""
    if d.month == 12:
        return d.replace(year=d.year + 1, month=1, day=1)
    return d.replace(month=d.month + 1, day=1)

def prev_month_first(d):
    """前月の1日を取得"""
    if d.month == 1:
        return d.replace(year=d.year - 1, month=12, day=1)
    return d.replace(month=d.month - 1, day=1)

today = date(2025, 1, 15)
print(next_month_first(today))  # 2025-02-01
print(prev_month_first(today))  # 2024-12-01

12月と1月の境界で年をまたぐ処理を忘れずに入れておきましょう。

dateutil を使うとシンプルに

dateutil ライブラリの relativedelta を使えば、月の加減算が簡単になります。

from datetime import date
from dateutil.relativedelta import relativedelta

today = date(2025, 1, 15)

# 翌月の1日
next_month = (today.replace(day=1) + relativedelta(months=1))
print(next_month)  # 2025-02-01

# 前月の1日
prev_month = (today.replace(day=1) - relativedelta(months=1))
print(prev_month)  # 2024-12-01

標準ライブラリの timedelta では months を指定できませんが、relativedelta なら直感的に月の加減算ができます。複雑な日付計算が多いプロジェクトでは、dateutil の導入を検討してみてください。