LoginSignup
2
1

More than 5 years have passed since last update.

拡張iso8601形式の日付をDataframeのindexに設定する方法

Last updated at Posted at 2016-12-19

なんだか苦労したのでメモしときます。

dt.ipynb
import pandas as pd

# JSTのサンプルデータ
data = [
    {"count":224, "time":"2016-01-01T09:00:00+0900"},
    {"count":198, "time":"2016-01-01T12:00:00+0900"},
    {"count":312, "time":"2016-01-01T20:00:00+0900"},
]
df = pd.DataFrame(data)
df

当然まだ文字列。

count time
0 224 2016-01-01T09:00:00+0900
1 198 2016-01-01T12:00:00+0900
2 312 2016-01-01T20:00:00+0900
dt.ipynb
# iso8601をto_datetime()に渡すとUTC時刻が返ってくるので、JSTに変換
dt = pd.to_datetime(df["time"].tolist()).tz_localize("UTC").tz_convert("Asia/Tokyo")
df.set_index(dt, inplace=True)
df.drop(["time"], axis=1, inplace=True)
df
count
2016-01-01 09:00:00+09:00 224
2016-01-01 12:00:00+09:00 198
2016-01-01 20:00:00+09:00 312
dt.ipynb
type(df.index)

pandas.tseries.index.DatetimeIndex

なんかもっとスマートな方法あれば知りたいなぁ・・・

2
1
0

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
2
1