numpy datetime64 add or substract date interval

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

Extracting the first day of month of a datetime type column in pandas

Simpliest and fastest is convert to numpy array by to_numpy and then cast: df[‘month’] = df[‘purchase_date’].to_numpy().astype(‘datetime64[M]’) print (df) user_id purchase_date month 0 1 2015-01-23 14:05:21 2015-01-01 1 2 2015-02-05 05:07:30 2015-02-01 2 3 2015-02-18 17:08:51 2015-02-01 3 4 2015-03-21 17:07:30 2015-03-01 4 5 2015-03-11 18:32:56 2015-03-01 5 6 2015-03-03 11:02:30 2015-03-01 Another solution with floor … Read more

Comparison between datetime and datetime64[ns] in pandas

For anyone who also stumbled across this when comparing a dataframe date to a variable date, and this did not exactly answer your question; you can use the code below. Instead of: self.df[“date”] = pd.to_datetime(self.df[“date”]) You can import datetime and then add .dt.date to the end like: self.df[“date”] = pd.to_datetime(self.df[“date”]).dt.date

Difference between data type ‘datetime64[ns]’ and ‘

datetime64[ns] is a general dtype, while <M8[ns] is a specific dtype. General dtypes map to specific dtypes, but may be different from one installation of NumPy to the next. On a machine whose byte order is little endian, there is no difference between np.dtype(‘datetime64[ns]’) and np.dtype(‘<M8[ns]’): In [6]: np.dtype(‘datetime64[ns]’) == np.dtype(‘<M8[ns]’) Out[6]: True However, on … Read more