概要
- 日付文字列をdatetime型に変換
- datetime型に変換した値から、年月列を追加
サンプルコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
df = pd.read_csv(r'./data/sample_date.csv') | |
print(df.dtypes) | |
df |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 日付文字列をdatetime型に変換 | |
df['register_date'] = pd.to_datetime(df['register_date']) | |
print(df.dtypes) | |
df |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 年月列を追加 | |
df['年月'] = df['register_date'].dt.strftime('%Y-%m') | |
print(df.dtypes) | |
df |
pandas.to_datetime の説明
- 引数
日付文字列
例)df['register_date'] などの日付文字列の配列を渡す使い方が多い - その他
pandas.Series.dt.strftime を使うと、引数に指定したフォーマットで日付文字列を返してくれる
例)df['年月'] = df['register_date'].dt.strftime('%Y-%m')
参考
https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html