高校物理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 の timedelta で日数・時間を加算・減算する

Python で日付や時刻に対して「3日後」や「2時間前」といった計算をするには、datetime モジュールの timedelta クラスを使います。

基本的な使い方

timedelta は日数や秒数などの「時間の長さ」を表すオブジェクトです。datetime オブジェクトに対して加算・減算することで、未来や過去の日時を求められます。

from datetime import datetime, timedelta

now = datetime.now()
print(f"現在: {now}")

# 3日後
three_days_later = now + timedelta(days=3)
print(f"3日後: {three_days_later}")

# 5日前
five_days_ago = now - timedelta(days=5)
print(f"5日前: {five_days_ago}")

timedelta(days=3) のように、キーワード引数で時間の長さを指定します。マイナスの値を渡すこともできますが、減算演算子を使うほうが直感的でしょう。

指定できる単位

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

weeks
days
hours時間
minutes
seconds
millisecondsミリ秒
microsecondsマイクロ秒

複数の単位を組み合わせた例を見てみましょう。

from datetime import datetime, timedelta

now = datetime.now()

# 1週間と3日後
delta = timedelta(weeks=1, days=3)
future = now + delta
print(f"1週間と3日後: {future}")

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

内部的には、すべての値が日数・秒・マイクロ秒の3つに正規化されて保持されます。そのため timedelta(hours=25)timedelta(days=1, hours=1) と同じ意味になります。

日付のみの date オブジェクトでも使える

datetime だけでなく、日付のみを扱う date オブジェクトに対しても timedelta は使えます。ただし、時間単位(hours や minutes)を指定しても日付部分にしか反映されません。

from datetime import date, timedelta

today = date.today()
print(f"今日: {today}")

# 1週間後
next_week = today + timedelta(weeks=1)
print(f"1週間後: {next_week}")

# 100日前
hundred_days_ago = today - timedelta(days=100)
print(f"100日前: {hundred_days_ago}")

日付の加減算は、締め切り計算やスケジュール管理でよく使うパターンです。timedelta を使いこなせば、面倒な日数計算から解放されます。