numpy datetime64添加或减少日期间隔 [英] numpy datetime64 add or substract date interval

查看:1936
本文介绍了numpy datetime64添加或减少日期间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一个巨大的ascii文件,其中包含分配给条目的日期。所以,我发现自己使用datetime包与numpy.datetime64并行添加数组功能。我知道大熊猫包可能最推荐用于日期,但是尝试拉开这个没有大熊猫的东西。我一直在寻找一个整洁的方法来添加/减去一个datestep像一年,或从datetime64对象3个月。



目前,我正在转换dt64对象到dt对象并使用replace函数来更改年份,例如,必须将其转换回dt64,这对我来说有点凌乱。所以,如果有人有一个更好的解决方案,只有numpy.datetime64格式,我将不胜感激。


示例:转换YYYY-12-31 到(YYYY-1)-12-31




  a = np.datetime64 (2014,12,31)#a是dt64对象
b = a.astype(object)#b是从
c = np.datetime64(b.replace(b.year-1))转换的dt对象)#c是dt64对象被移回1年(1年)


解决方案

您可以使用numpy.timedelta64对象对numpy.datetime64对象执行时间增量计算,请参阅日期时间和Timedelta算术



一年可能是365天或366天,不可能减少一年,但您可以减少365天:

  import numpy as np 
np.datetime64('2014-12-31') - np.timedelta64(365 ,'D')

结果为:



numpy.datetime64('2013-12-31')


I am parsing a huge ascii file with dates assigned to entries. So, I found myself using datetime package in parallel to numpy.datetime64 to add array capabilities. I know that the pandas package is probably most recommended to be used for date, however try to pull this off without pandas. I have been looking around for a neat way to add/subtract a certain datestep like one year, or 3 month from a datetime64 object.

Currently, I am converting dt64 object to dt object and use replace function to change the year for example and have to convert it back to dt64 afterward which is a bit messy to me. So, I would appreciate if anyone has a better solution using only numpy.datetime64 format.

Example: Converting a "YYYY-12-31" to "(YYYY-1)-12-31"

a = np.datetime64(2014,12,31)               # a is dt64 object
b = a.astype(object)                        # b is dt object converted from a
c = np.datetime64( b.replace(b.year-1))     # c is dt64 object shifted back 1 year (a -1year)

解决方案

You can use the numpy.timedelta64 object to perform time delta calculations on a numpy.datetime64 object, see Datetime and Timedelta Arithmetic.

Since a year can be either 365 or 366 days, it is not possible to substract a year, but you could substract 365 days instead:

import numpy as np
np.datetime64('2014-12-31') - np.timedelta64(365,'D')

results in:

numpy.datetime64('2013-12-31')

这篇关于numpy datetime64添加或减少日期间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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