Converting between datetime, Timestamp and datetime64

前端 未结 12 1281
傲寒
傲寒 2020-11-22 01:43

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)?

In the following code, I create a datetime,

12条回答
  •  灰色年华
    2020-11-22 02:18

    indeed, all of these datetime types can be difficult, and potentially problematic (must keep careful track of timezone information). here's what i have done, though i admit that i am concerned that at least part of it is "not by design". also, this can be made a bit more compact as needed. starting with a numpy.datetime64 dt_a:

    dt_a

    numpy.datetime64('2015-04-24T23:11:26.270000-0700')

    dt_a1 = dt_a.tolist() # yields a datetime object in UTC, but without tzinfo

    dt_a1

    datetime.datetime(2015, 4, 25, 6, 11, 26, 270000)

    # now, make your "aware" datetime:
    

    dt_a2=datetime.datetime(*list(dt_a1.timetuple()[:6]) + [dt_a1.microsecond], tzinfo=pytz.timezone('UTC'))

    ... and of course, that can be compressed into one line as needed.

提交回复
热议问题