在datetime,Timestamp和datetime64之间进行转换

问题:

如何将numpy.datetime64对象转换为datetime.datetime(或Timestamp)?
在下面的代码中,我创建一个datetime,timestamp和datetime64对象。

import datetime
import numpy as np
import pandas as pd
dt = datetime.datetime(2012, 5, 1)
# A strange way to extract a Timestamp object, there's surely a better way?
ts = pd.DatetimeIndex([dt])[0]
dt64 = np.datetime64(dt)

In [7]: dt
Out[7]: datetime.datetime(2012, 5, 1, 0, 0)

In [8]: ts
Out[8]: <Timestamp: 2012-05-01 00:00:00>

In [9]: dt64
Out[9]: numpy.datetime64('2012-05-01T01:00:00.000000+0100')

 Note: it’s easy to get the datetime from the Timestamp:

In [10]: ts.to_datetime()
Out[10]: datetime.datetime(2012, 5, 1, 0, 0)

但是我们如何从numpy.datetime64dt64)中提取datetimeTimestamp
更新:我的数据集中有一个令人讨厌的例子(也许是激励的例子)似乎是:

dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')

这应该是datetime.datetime(2002, 6, 28, 1, 0),而不是一个长(!)(1025222400000000000L)…

回答:

要将numpy.datetime64转换为代表UTC时间的numpy-1.8的日期时间对象

>>> from datetime import datetime
>>> import numpy as np
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> dt64 = np.datetime64(dt)
>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
>>> ts
1354650685.3624549
>>> datetime.utcfromtimestamp(ts)
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> np.__version__
'1.8.0.dev-7b75899'

上面的例子假设一个天真的datetime对象是以UTC为时间解释的。
要将datetime转换为np.datetime64并返回(numpy-1.6):

>>> np.datetime64(datetime.utcnow()).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)

它在单个np.datetime64对象和nump.natdatetime64数组上工作。
想想np.datetime64的方式与np.int8,np.int16等相同,并且应用相同的方法来转换诸如int,datetime和相应的numpy对象之类的Python对象。
你的“讨厌的例子”工作正常:

>>> from datetime import datetime
>>> import numpy 
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__
'1.6.2' # current version available via pip install numpy

我可以将numpy-1.8.0上的long值重新安装为:

pip install git+https://github.com/numpy/numpy.git#egg=numpy-dev

同样的例子:

>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
1025222400000000000L
>>> numpy.__version__
'1.8.0.dev-7b75899'

它返回long,因为numpy.datetime64类型.astype(datetime)等价于.astype(object)numpy-1.8上返回Python整数(long)。
要获取datetime对象,您可以:

>>> dt64.dtype
dtype('<M8&#91;ns&#93;')
>>> ns = 1e-9 # number of seconds in a nanosecond
>>> datetime.utcfromtimestamp(dt64.astype(int) * ns)
datetime.datetime(2002, 6, 28, 0, 0)

要直接使用秒的datetime64:

>>> dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
>>> dt64.dtype
dtype('<M8&#91;s&#93;')
>>> datetime.utcfromtimestamp(dt64.astype(int))
datetime.datetime(2002, 6, 28, 0, 0)

numpy docs表示datetime API是实验性的,可能会在将来的numpy版本中更改。

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Converting between datetime, Timestamp and datetime64

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

84 − = 83