numpy - 将 numpy.datetime64 转换为纪元时间

标签 numpy python-3.6 epoch

我正在尝试将包含 numpy.datetime64 的 numpy 数组 new_feat_dt 转换为纪元时间。我想确保转换发生时日期保持 utc 格式? 我正在使用 numpy 1.16.4 和 python3.6 我尝试了两种转换方式,如下面的代码所示。

import numpy as np
new_feat_dt = [np.datetime64('2019-07-25T14:23:01'), np.datetime64('2019-07-25T14:25:01'), np.datetime64('2019-07-25T14:27:01')]

final= [(x - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') for x in new_feat_dt]
print (final)
print(type(final[0]))

final2= [np.datetime64(x,'s').astype(int)  for x in new_feat_dt]
print (final2)
print(type(final2[0]))

上述代码的输出:

[1564064581.0, 1564064701.0, 1564064821.0]
<class 'numpy.float64'>
[1564064581, 1564064701, 1564064821]
<class 'numpy.int32'>

发生上述情况是因为 new_feat_dt 数组中的时间被视为 GMT。我希望将其视为我的本地时间(“美国/东部时间”)。 正确的转换应该是这样的: [1564078981,1564079101,1564079221]

最佳答案

numpy.datetime64timezone naive datetime type 。要将时区信息添加到日期时间中,请尝试使用 python 的 datetimepytz 模块。

import numpy as np
import pytz
from datetime import datetime
new_feat_dt = [np.datetime64('2019-07-25T14:23:01'), np.datetime64('2019-07-25T14:25:01'), np.datetime64('2019-07-25T14:27:01')]
eastern = pytz.timezone('US/Eastern')
final = [int(eastern.localize(dt.astype(datetime)).timestamp()) for dt in new_feat_dt]
print(final)

输出:

[1564078981, 1564079101, 1564079221]

最好使用 datetime.datetime 初始化所有 new_feat_dt

关于numpy - 将 numpy.datetime64 转换为纪元时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57208280/

相关文章:

date - Groovy - 将时间戳字符串转换为以毫秒为单位的纪元时间

python - python中的莱文森算法

python - 传播计算结果

python - float64 到 float32 的转换给出了意想不到的结果

python - 苹果系统; Python3; FileNotFoundError : [Errno 2] No such file or directory: '' . 如何修复?

python - 尝试失败,但代码不执行

python - 了解 __init_subclass__

perl - 如何在 Perl 中将纪元时间转换为正常时间?

python - 乘以一元素矩阵

pandas - 将几列转换为 epoch pandas