如何将numpy datetime64 [ns]转换为python datetime? [英] How to convert numpy datetime64 [ns] to python datetime?

查看:587
本文介绍了如何将numpy datetime64 [ns]转换为python datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert dates from pandas frame values in the separate function:

 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?

How to convert numpy datetime64 [ns] to python datetime?

推荐答案

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

I wonder if you need all this conversion work. With the right time units a datetime64 can produce a datetime object directly.

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

I'm not sure about your when variable, but let's assume it comes from pandas, and is something like a 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],结果是一个大整数,某种形式的时间戳".但是,如果我将时间单位转换为秒,甚至是微秒(美国),就可以了:

With [ns] the result is a large integer, a 'timestamp' of some sort. But if I convert the time units to something like seconds, or even microseconds (us):

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个对象的列表.

这篇关于如何将numpy datetime64 [ns]转换为python datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆