LoginSignup
1
2

More than 3 years have passed since last update.

0埋めされていない年月日を、正規表現でdatetime型に変換

Last updated at Posted at 2020-04-14

pythonのdatetimeには、文字列型をdatetime型に変換する関数strptime() があるが、0埋めされていない文字列は変換できない。
2020/04/03は変換できるけど2020/4/3はできない)

その簡単な代替方法があったのでメモ。

全角が含まれる場合は、何らかの方法で全角を半角にしてから実行。
方法はいろいろあるのでお好みのものを。

コード

strptime()の代わりに、datetimeのコンストラクタを用いる。
https://docs.python.org/ja/3/library/datetime.html#datetime.datetime

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

import datetime
import re

# 文字列に含まれる数字のリストを取得
l = re.findall(r"\d+", text)

# 文字列のリストを数値のリストにする
l = [int(s) for s in l]

# datetime型のコンストラクタで、日時を指定(リストを展開して渡す)
date = datetime.datetime(*l)

サンプル

import datetime
import re

text = "2020/4/2"
l = re.findall(r"\d+", text)
# l : ["2020", "4", "2"]

l = [int(s) for s in l]
# l : [2020, 4, 2]

date = datetime.datetime(*l)
# date = datetime.datetime(2020, 4, 2)

おまけ

和暦 to 西暦の変換にも使えるかも
("元年"に対応させる必要はあり)

import datetime
import re

text = "令和2年4月3日"

diff = 0
if text[:2]=="令和":
    diff = 2018
else:
    # hoge
    pass

l = re.findall(r"\d+", text)
l = [int(s) for s in l]

l[0] += diff
date = datetime.datetime(*l)

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2