3
3

More than 3 years have passed since last update.

numpy.datetime64をPythonのdatetime.datetime型にキャストする

Last updated at Posted at 2021-02-11

TL;DR


import datetime

# numpy_datetime = numpy.datetime64型の変数
python_datetime = datetime.datetime.fromtimestamp(numpy_datetime.astype(datetime.datetime) * 1e-9)

参考:https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64

補足

  • たとえばpandasでエクセルデータをDataFrameにしたとする。その際、セルのデータ型が日時だと、numpy.datetime64にキャストされる。
  • これをPythonのdatetime.datetime型にするのはすこしめんどくさかった。結論として、numpy.datetime64 -> unixtime -> datetime.datetimeと変換すればよい
  • numpy.datetime64を.astype(datetime.datetime)とするとUNIX timeに変換されるが、この値はint型であり、一方Pythonのdatetime.datetimeのunixtimeはFloat型である(この差は、精度とか計算効率の話かな?)。
  • なのでnumpy-unixtimeに1e-9をかけて、Python-unixtimeと桁を合わせてから、datetime.datetime.fromtimestanp(unixtime)でPythonのdatetime.datetime型が得られる
3
3
2

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
3
3