高校物理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 で ISO 8601 形式の文字列を datetime にパースする

ISO 8601 は日時の国際標準フォーマットで、API やデータ交換で広く使われています。Python で ISO 8601 形式の文字列を datetime にパースする方法を解説します。

ISO 8601 とは

ISO 8601 は 2025-01-15T10:30:00+09:00 のような形式で日時を表します。

日付部分2025-01-15(年-月-日)
区切り文字T
時刻部分10:30:00(時:分:秒)
タイムゾーン+09:00 または Z(UTC)

T は日付と時刻の区切りを示し、末尾のタイムゾーン情報で世界中どこでも一意に時刻を特定できます。

fromisoformat() を使う

Python 3.7 以降、datetime.fromisoformat() で ISO 8601 形式を簡単にパースできます。

from datetime import datetime

# 基本形式
s = "2025-01-15T10:30:00"
dt = datetime.fromisoformat(s)
print(dt)  # 2025-01-15 10:30:00

# タイムゾーン付き
s = "2025-01-15T10:30:00+09:00"
dt = datetime.fromisoformat(s)
print(dt)  # 2025-01-15 10:30:00+09:00

strptime() のように書式を指定する必要がなく、コードがシンプルになります。

Z(Zulu タイム)への対応

UTC を表す Z は、Python 3.11 以降で fromisoformat() が直接対応しました。それ以前のバージョンでは置換が必要です。

from datetime import datetime, timezone

s = "2025-01-15T10:30:00Z"

# Python 3.11 以降はそのまま OK
# dt = datetime.fromisoformat(s)

# 3.10 以前は Z を +00:00 に置換
s_replaced = s.replace("Z", "+00:00")
dt = datetime.fromisoformat(s_replaced)
print(dt)  # 2025-01-15 10:30:00+00:00

互換性を考慮するなら、Z の置換処理を入れておくのが安全です。

strptime() でパースする

fromisoformat() が使えない環境や、より細かい制御が必要な場合は strptime() を使います。

from datetime import datetime

# タイムゾーンなし
s = "2025-01-15T10:30:00"
dt = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S")
print(dt)

# タイムゾーンあり(Python 3.2 以降)
s = "2025-01-15T10:30:00+0900"
dt = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S%z")
print(dt)

%z はタイムゾーンオフセットに対応しますが、+09:00 形式ではなく +0900 形式(コロンなし)を期待する点に注意してください。

ミリ秒・マイクロ秒を含む場合

ISO 8601 では小数秒も許容されています。

from datetime import datetime

# マイクロ秒付き
s = "2025-01-15T10:30:00.123456"
dt = datetime.fromisoformat(s)
print(dt)  # 2025-01-15 10:30:00.123456

# ミリ秒(3桁)も OK
s = "2025-01-15T10:30:00.123"
dt = datetime.fromisoformat(s)
print(dt)  # 2025-01-15 10:30:00.123000

fromisoformat() は3桁から6桁までの小数秒を自動で処理してくれます。

datetime から ISO 8601 へ

逆方向の変換は isoformat() メソッドを使います。

from datetime import datetime, timezone

dt = datetime(2025, 1, 15, 10, 30, 0, tzinfo=timezone.utc)
iso_string = dt.isoformat()
print(iso_string)  # 2025-01-15T10:30:00+00:00

API へのリクエストやログ出力で、標準化されたフォーマットが必要なときに活用できます。