Converting between datetime, Timestamp and datetime64

前端 未结 12 1528
傲寒
傲寒 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:09

    I've come back to this answer more times than I can count, so I decided to throw together a quick little class, which converts a Numpy datetime64 value to Python datetime value. I hope it helps others out there.

    from datetime import datetime
    import pandas as pd
    
    class NumpyConverter(object):
        @classmethod
        def to_datetime(cls, dt64, tzinfo=None):
            """
            Converts a Numpy datetime64 to a Python datetime.
            :param dt64: A Numpy datetime64 variable
            :type dt64: numpy.datetime64
            :param tzinfo: The timezone the date / time value is in
            :type tzinfo: pytz.timezone
            :return: A Python datetime variable
            :rtype: datetime
            """
            ts = pd.to_datetime(dt64)
            if tzinfo is not None:
                return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, tzinfo=tzinfo)
            return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
    

    I'm gonna keep this in my tool bag, something tells me I'll need it again.

提交回复
热议问题