この記事は何
日付や時間が書かれている文字列をdatetime型に変換して、時間の差分などを求める。
環境:python3.8.5, Mac OS X
文字列→datetimeへの変換
- 参考文献
指定フォーマットで文字列→datetimeの変換を行う
strptime
を用いて変換を行う。datetimeに変換したい文字列とタイムスタンプのフォーマット(下の例では '%Y/%m/%d'
)を引数に渡す。
from datetime import datetime # 日付文字列を作成 sample_date_str = [f"2020/1/{day+1}" for day in range(10)] # datetimeに変換する sample_datetime = [datetime.strptime(datestr, '%Y/%m/%d') for datestr in sample_date_str] print(sample_date_str) print(sample_datetime)
['2020/1/1', '2020/1/2', '2020/1/3', '2020/1/4', '2020/1/5', '2020/1/6', '2020/1/7', '2020/1/8', '2020/1/9', '2020/1/10'] [datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 2, 0, 0), datetime.datetime(2020, 1, 3, 0, 0), datetime.datetime(2020, 1, 4, 0, 0), datetime.datetime(2020, 1, 5, 0, 0), datetime.datetime(2020, 1, 6, 0, 0), datetime.datetime(2020, 1, 7, 0, 0), datetime.datetime(2020, 1, 8, 0, 0), datetime.datetime(2020, 1, 9, 0, 0), datetime.datetime(2020, 1, 10, 0, 0)]
複数の時間フォーマットを同時に変換する
一つずつ順番に試す
上記の例の場合は全ての文字列のフォーマットがきれいに整っていたのでエラーなく変換できたが、上のコードはフォーマットが異なる文字列が一つでも含まれるとValueErrorになってしまう。複数の指定フォーマットを適用する場合は一つずつチェックする。
def convert_str_to_datetime(datestr:str, default_datetime:datetime=datetime(1970, 1, 1)) -> datetime: """文字列からdatetimeに変換を行う Args: datestr (string): 日付が書かれた文字列 default_datetime (datetime): 変換失敗時に返されるdatetime. Default is 1970, 1, 1. Return: datetime """ ymd_formats = ['%Y/%m/%d', '%Y-%m-%d', '%Y年%m月%d日', '%Y %m %d'] for ymdf in ymd_formats: try: res = datetime.strptime(datestr, ymdf) return res except ValueError: continue return default_datetime print(convert_str_to_datetime("2000/1/1")) print(convert_str_to_datetime("2000-1-1")) print(convert_str_to_datetime("2000年1月1日")) print(convert_str_to_datetime("2000X1X1X"))
出力:
2000-01-01 00:00:00 2000-01-01 00:00:00 2000-01-01 00:00:00 1970-01-01 00:00:00
python-dateutilを使う
年月日以降の時・分・秒がきてもパースできる。ただし、パースできない文字列はValueErrorになる。
import dateutil.parser as dp print(dp.parse("2000/1/1")) print(dp.parse("2000-1-1")) print(dp.parse("20000101"))
出力:
2000-01-01 00:00:00 2000-01-01 00:00:00 2000-01-01 00:00:00
datetimeに対する処理
日本・海外の祝日
それぞれ必要なパッケージをインストールして使用する。
pandasでの特徴作成
pandas.Series.dt.date — pandas 1.2.3 documentation
pandas.Series.dt.XXX
を参照する。日付や曜日など基本的な特徴はすぐに作成できる。
例えばdataframeの列に含まれる日付を求めるときは、.dt.day
でもとまる。
import pandas as pd import dateutil.parser as dp # 日付の文字列 date_str_series = pd.Series([f"2020/1/{day+1}" for day in range(10)]) # datetimeに変換 date_datetime_series = date_str_series.apply(lambda d: dp.parse(d)) # 日付を求める date_datetime_series_day = date_datetime_series.dt.day print(date_str_series) # 元の文字列 print(date_datetime_series_day) # 日付を求めたもの
出力:
0 2020/1/1 1 2020/1/2 2 2020/1/3 3 2020/1/4 4 2020/1/5 5 2020/1/6 6 2020/1/7 7 2020/1/8 8 2020/1/9 9 2020/1/10 dtype: object 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 dtype: int64
複数のタイムスタンプの時間間隔を調べる
pandas.Series.diff
を用いる。これは直前のデータとの差分を求めるAPIで、datetimeについても差を求めることができる。
import pandas as pd import dateutil.parser as dp date_str_series = pd.Series([f"2020/1/{day+1}" for day in range(10)]) date_datetime_series = date_str_series.apply(lambda d: dp.parse(d)) print(date_datetime_series.diff())
出力:
0 NaT 1 1 days 2 1 days 3 1 days 4 1 days 5 1 days 6 1 days 7 1 days 8 1 days 9 1 days dtype: timedelta64[ns]
datetime→文字列
datetime --- 基本的な日付型および時間型 — Python 3.8.8 ドキュメント
date.strftime(format)
明示的な書式文字列で制御された、日付を表現する文字列を返します。 時間、分、秒を表す書式コードは値 0 になります。
上記ドキュメントに使用例が載っているので省略。