将numpy的datetime64转换为长整型数并再次转换回来

7
如何将NumPy datetime64转换为长整数并进行反向转换?
import numpy as np
import datetime

np.datetime64(datetime.datetime.now()).astype(long)

给出了一个值为1511975032478959

np.datetime64(np.datetime64(datetime.datetime.now()).astype(long))

产生错误:
ValueError: Converting an integer to a NumPy datetime requires a specified unit
3个回答

7

您需要指定long int的单位(在本例中为微秒)。

 np.datetime64(np.datetime64(datetime.datetime.now()).astype(long), 'us')

返回值
 numpy.datetime64('2017-11-29T17:11:44.638713')

我通过将“us”作为第二个参数添加来解决了这个问题。不管怎样,谢谢你。 - Inquisitor
NameError: 名称“long”未定义 - RogerS

4
'

'us'转换为微秒。如果您需要不同的格式,请使用:enter image description here

此处所示。

'

0
这对我在Python3中有效(其他答案似乎专注于Python2):
now = datetime.datetime.now().timestamp()
np.datetime64(int(now),'s')

2022年07月01日14:25:22


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接