高校物理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 で「3日後」「2時間前」を計算する timedelta 入門

timedelta は Python の日時操作で欠かせないクラスです。この記事では、初心者向けに基本から丁寧に解説します。

timedelta とは

timedelta は「時間の長さ」を表すオブジェクトです。「3日間」「2時間」「30分」といった期間を表現できます。日時を表す datetime とは異なり、特定の時点ではなく時間の幅を扱う点が特徴です。

datetime

「2025年1月15日 10時30分」のような特定の時点を表す

timedelta

「3日間」「2時間30分」のような時間の長さを表す

3日後を求める

現在時刻から3日後を求めてみましょう。

from datetime import datetime, timedelta

now = datetime.now()
three_days_later = now + timedelta(days=3)

print(f"現在: {now}")
print(f"3日後: {three_days_later}")

timedelta(days=3) で「3日間」を表すオブジェクトを作り、datetime に加算しています。足し算の感覚で未来の日時が得られるのは直感的ですね。

2時間前を求める

過去の日時は引き算で求めます。

from datetime import datetime, timedelta

now = datetime.now()
two_hours_ago = now - timedelta(hours=2)

print(f"現在: {now}")
print(f"2時間前: {two_hours_ago}")

引き算を使うことで、指定した時間だけ過去に遡れます。ログの時刻計算や、「○分以内の更新」といった判定によく使われるパターンです。

複合的な指定

timedelta は複数の単位を同時に指定できます。

from datetime import datetime, timedelta

now = datetime.now()

# 1日と12時間後
future = now + timedelta(days=1, hours=12)
print(f"1日12時間後: {future}")

# 1時間30分前
past = now - timedelta(hours=1, minutes=30)
print(f"1時間30分前: {past}")

業務でよくある「翌営業日の午前中まで」といった期限計算も、この組み合わせで表現できます。

よくあるミス

timedelta には「月」や「年」の単位がありません。

from datetime import timedelta

# これはエラーになる
# delta = timedelta(months=1)  # TypeError
# delta = timedelta(years=1)   # TypeError

月や年は日数が固定でないため、標準ライブラリでは扱えないのです。「1ヶ月後」を求めたい場合は、dateutil ライブラリの relativedelta を使う必要があります。

timedelta は日・時・分・秒の範囲では非常に便利なので、まずはこの基本をしっかり押さえておきましょう。