numpy datetime64添加或减少日期间隔 [英] numpy datetime64 add or substract date interval
问题描述
目前,我正在转换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屋!