【Python】文字列を日付型に変える|datetime.strptime
作成日:2025-10-06
更新日:2025-10-06

datetime
を使うdatetime.strptime()
でフォーマットを明示してパースする
from datetime import datetime
def create_date_from_str(s: str) -> datetime:
"""Convert a flexible date string (with '/', '-', or '.') into datetime safely.
柔軟な区切り文字(日付文字列)を安全に datetime に変換する
"""
# Normalize delimiters|区切り文字を統一
s = s.replace('-', '/').replace('.', '/')
try:
# Try standard format|標準フォーマットを試す
return datetime.strptime(s, "%Y/%m/%d")
except ValueError:
# Validation failed|不正な日付
raise ValueError(f"Invalid date format: {s}")
区切り文字が混ざる場合は、正規化してから処理すると安全
Example Usage|使用例
print(create_date_from_str("2025/10/06"))
print(create_date_from_str("2025-10-06"))
print(create_date_from_str("2025.10.6"))
print(create_date_from_str("2025/1/6"))
▶ 出力結果
2025-10-06 00:00:00
2025-10-06 00:00:00
2025-10-06 00:00:00
2025-01-06 00:00:00
不正日付の場合
create_date_from_str("2025/13/40")
→ ValueError: Invalid date format: 2025/13/40
Vocabulary
| datetime.strptime|文字列から日付を生成 |
| ValueError|値エラー |
| Normalize|正規化する |
| Exception Handling|例外処理 |
| Datetime Object|日付オブジェクト |
In Python, always use
datetime.strptime()
— not string slicing.
2025-10-06
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[Python]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame -
[Python]pathlib存在確認 【Python】フォルダとファイルの存在確認|pathlib -
[Python]pathlibfor extension 【Python】文字列から拡張子を取得して、文字列で返す|pathlib.Path.suffix -
[Python]inString 【Python】指定の文字列が含まれているか|in -
[Python]list concatenation 【Python】配列(list)の結合|arr + arr , np.concatenate -
[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv