Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy datetime64 add or substract date interval

Tags:

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) 
like image 876
Moe Avatar asked Apr 03 '14 15:04

Moe


People also ask

What is Numpy datetime64?

datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy. datetime64() method. Syntax : numpy.datetime64(date) Return : Return the date in a format 'yyyy-mm-dd'.

How do I convert datetime64 to datetime?

After that, You can create datetime64 format using the numpy. datetime64() format. To convert it to datetime format then you have to use astype() method and just pass the datetime as an argument.

How do you get all dates corresponding to the month of July 2016 in Numpy?

In NumPy to display all the dates for a particular month, we can do it with the help of NumPy. arrange() pass the first parameter the particular month and the second parameter the next month and the third parameter is the datatype datetime64[D]. It will return all the dates for the particular month.

What is Timedelta64?

Timedelta64 computations between two UTC dates can be wrong by an integer number of SI seconds. Example. Compute the number of SI seconds between “2021-01-01 12:56:23.423 UTC” and “2001-01-01 00:00:00.000 UTC”: >>> ( ... np.


1 Answers

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')

like image 76
Puggie Avatar answered Oct 15 '22 18:10

Puggie