LoginSignup
8
6

More than 5 years have passed since last update.

pandasでunix時刻をdatetime型に変更する際の注意事項

Last updated at Posted at 2016-01-02

下記テーブルのようなpd.DataFrame型(indexにunix時刻が入っている)があった時に,int型のtimestampをその後の処理上,datetime型に変更したいが,
pandasに用意されている関数をそのまま使うと,おかしな結果になってしまったので備忘録.

x y z
timestamp
1450407402547 -2.153091 1.582626 9.288803
1450407402577 -2.368118 1.287659 9.227219
1450407402607 -3.023911 4.160522 8.133606
1450407402637 -2.316528 2.467163 9.581879
convert.py
df["time"] = pd.to_datetime(df.index , unit="ms")
df["time2"] =df.index
df["time3"] = df.time2.apply(lambda x: datetime.fromtimestamp(x/1000))

x y z time time2 time3
timestamp
1450407402547 -2.153091 1.582626 9.288803 2015-12-18 02:56:42.547 1450407402547 2015-12-18 11:56:42.546999
1450407402577 -2.368118 1.287659 9.227219 2015-12-18 02:56:42.577 1450407402577 2015-12-18 11:56:42.576999
1450407402607 -3.023911 4.160522 8.133606 2015-12-18 02:56:42.607 1450407402607 2015-12-18 11:56:42.607000
1450407402637 -2.316528 2.467163 9.581879 2015-12-18 02:56:42.637 1450407402637 2015-12-18 11:56:42.637000

time2は下記のようにするとエラーが出たので無理やり作った.

df["time3"] = df.index.apply(lambda x: datetime.fromtimestamp(x/1000))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-117-0c598f05317f> in <module>()
----> 1 df["time3"] = df.index.apply(lambda x: datetime.fromtimestamp(x/1000))

AttributeError: 'Int64Index' object has no attribute 'apply'

上記の結果からtime3のやり方だと正しくunix時刻が変換される.

pd.to_datetimeの仕様を確認せねば...

8
6
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
8
6