Converting between datetime, Timestamp and datetime64

前端 未结 12 1305
傲寒
傲寒 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 01:59

    One option is to use str, and then to_datetime (or similar):

    In [11]: str(dt64)
    Out[11]: '2012-05-01T01:00:00.000000+0100'
    
    In [12]: pd.to_datetime(str(dt64))
    Out[12]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))
    

    Note: it is not equal to dt because it's become "offset-aware":

    In [13]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
    Out[13]: datetime.datetime(2012, 5, 1, 1, 0)
    

    This seems inelegant.

    .

    Update: this can deal with the "nasty example":

    In [21]: dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')
    
    In [22]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
    Out[22]: datetime.datetime(2002, 6, 28, 1, 0)
    

提交回复
热议问题