Converting between datetime, Timestamp and datetime64

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

    Some solutions work well for me but numpy will deprecate some parameters. The solution that work better for me is to read the date as a pandas datetime and excract explicitly the year, month and day of a pandas object. The following code works for the most common situation.

    def format_dates(dates):
        dt = pd.to_datetime(dates)
        try: return [datetime.date(x.year, x.month, x.day) for x in dt]    
        except TypeError: return datetime.date(dt.year, dt.month, dt.day)
    
    0 讨论(0)
  • 2020-11-22 02:13
    >>> dt64.tolist()
    datetime.datetime(2012, 5, 1, 0, 0)
    

    For DatetimeIndex, the tolist returns a list of datetime objects. For a single datetime64 object it returns a single datetime object.

    0 讨论(0)
  • 2020-11-22 02:14

    If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime().

    pd.date_range('20110101','20110102',freq='H').to_pydatetime()
    
    > [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
       datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
       ....
    

    It also supports timezones:

    pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()
    
    [ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
     datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
    ....
    

    NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime() on the entire series. You will need to call .to_pydatetime() on each individual datetime64 using a list comprehension or something similar:

    datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]
    
    0 讨论(0)
  • 2020-11-22 02:14
    import numpy as np
    import pandas as pd 
    
    def np64toDate(np64):
        return pd.to_datetime(str(np64)).replace(tzinfo=None).to_datetime()
    

    use this function to get pythons native datetime object

    0 讨论(0)
  • 2020-11-22 02:16

    This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.

    I have come across another way to do the conversion that only involves modules numpy and datetime, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime) will return a datetime.datetime object if the original datetime64 is in micro-second units while other units return an integer timestamp. I use module xarray for data I/O from Netcdf files which uses the datetime64 in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,

    import numpy as np
    import datetime
    
    def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
        t = np.datetime64( usert, 'us').astype(datetime.datetime)
    return t
    

    Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题