如何将numpy datetime64 [ns]转换为python datetime?

时间:2018-10-25 05:41:26

标签: python numpy

我需要在单独的函数中从熊猫框架值转换日期:

 def myfunc(lat, lon, when):
        ts = (when - np.datetime64('1970-01-01T00:00:00Z','s')) / np.timedelta64(1, 's')
        date = datetime.datetime.utcfromtimestamp(ts)
        print("Numpy date= ", when, " Python date= ", date)
        return float(90) - next_func(lat, lon, date)

调用此功能:

new_df['new_column'] =  np.vectorize(my_func)(lat, lon, new_df['datetime(LT)'])  

但是它会引发错误:

ufunc subtract cannot use operands with types dtype('int64') and dtype('<M8[s]')

如何将numpy datetime64 [ns]转换为python datetime?

3 个答案:

答案 0 :(得分:1)

我想知道您是否需要所有这些转换工作。在正确的时间单位下,datetime64可以直接产生一个datetime对象。

我不确定您的when变量,但是我们假设它来自pandas,类似于DatetimeIndex

In [56]: time = pandas.date_range('6/28/2013', periods=5, freq='5D')
In [57]: time
Out[57]: 
DatetimeIndex(['2013-06-28', '2013-07-03', '2013-07-08', '2013-07-13',
               '2013-07-18'],
              dtype='datetime64[ns]', freq='5D')

等效的numpy数组

In [58]: time.values
Out[58]: 
array(['2013-06-28T00:00:00.000000000', '2013-07-03T00:00:00.000000000',
       '2013-07-08T00:00:00.000000000', '2013-07-13T00:00:00.000000000',
       '2013-07-18T00:00:00.000000000'], dtype='datetime64[ns]')
In [59]: time.values.tolist()
Out[59]: 
[1372377600000000000,
 1372809600000000000,
 1373241600000000000,
 1373673600000000000,
 1374105600000000000]

对于[ns],结果是一个大整数,某种形式的“时间戳”。但是,如果我将时间单位转换为秒,甚至是微秒(美国),则为

In [60]: time.values.astype('datetime64[s]')
Out[60]: 
array(['2013-06-28T00:00:00', '2013-07-03T00:00:00',
       '2013-07-08T00:00:00', '2013-07-13T00:00:00',
       '2013-07-18T00:00:00'], dtype='datetime64[s]')
In [61]: time.values.astype('datetime64[s]').tolist()
Out[61]: 
[datetime.datetime(2013, 6, 28, 0, 0),
 datetime.datetime(2013, 7, 3, 0, 0),
 datetime.datetime(2013, 7, 8, 0, 0),
 datetime.datetime(2013, 7, 13, 0, 0),
 datetime.datetime(2013, 7, 18, 0, 0)]

结果是datetime个对象的列表。

答案 1 :(得分:1)

我更喜欢这种解决方法,因为有时np.datetime64具有不同的分辨率

def ___convert_to_datetime(d):
    return datetime.strptime(np.datetime_as_string(d,unit='s'), '%Y-%m-%dT%H:%M:%S')

获取时间戳

def ___convert_to_ts(d):
    return datetime.strptime(np.datetime_as_string(d,unit='s'), '%Y-%m-%dT%H:%M:%S').timestamp()

例如

import numpy as np
from datetime import datetime


def ___convert_to_datetime(d):
  return datetime.strptime(np.datetime_as_string(d,unit='s'), '%Y-%m-%dT%H:%M:%S')



def ___convert_to_ts(d):
  return datetime.strptime(np.datetime_as_string(d,unit='s'), '%Y-%m-%dT%H:%M:%S').timestamp()


print(___convert_to_datetime(np.datetime64('2005-02-25')))

my_ns_date = np.datetime64('2009') + np.timedelta64(20, 'ns')

print(my_ns_date)

print(___convert_to_datetime(my_ns_date))

输出将为

2005-02-25 00:00:00

2009-01-01T00:00:00.000000020

2009-01-01 00:00:00

答案 2 :(得分:0)

def myfunc(lat, lon, when):
    ts = (when - np.datetime64('1970-01-01T00:00:00Z','s')) / np.timedelta64(1, 's')
    date = datetime.utcfromtimestamp(ts)
    print("Numpy date= ", when, " Python date= ", date)
    return float(90) - next_func(lat, lon, date)

尝试此代码

要将numpy datetime64 [ns]转换为python datetime,只需尝试以下代码段

from datetime import datetime
datetime.utcfromtimestamp('your_time_stamp')