extracting days from a numpy.timedelta64 value
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
Or, as @PhillipCloud suggested, just days.astype(int)
since the timedelta
is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D'
, 'ns'
, ...).You can find more about it here.
how to extract days as integers from a timedelta64[ns] object in python
This should convert your timedelta64[ns]
type to float64
representing days:
data['difference'].astype('timedelta64[D]')
how to convert timedelta64 to number of days integer?
For a single value, you can use Timedelta.days
td = pd.to_timedelta('146 days 12:37:08.787241')
td.days
146
However, for a pandas Series
of Timedeltas you'll need the dt
accessormy_pd_series.dt.days
How to get the number value from timedelta64
use parameter ms
inside np.datetime64(datetime,'ms') as second then do subtraction
first_date = np.datetime64("2013-04-08 15:52:17.207",'ms')
last_date = np.datetime64("2013-05-29 10:44:44",'ms')
a=last_date-first_date
b=a.astype('int')
type(b)
Time difference in seconds from numpy.timedelta64
You can access it through the "wrapped" datetime item:
>>> dt.item().total_seconds()
65.0
Explanation: here dt
is an array scalar in numpy
, which is a zero rank array or 0-dimensional array. So you will find the dt
here also has all the methods an ndarray possesses, and you can do for example dt.astype('float')
. But it wraps a python object, in this case a datetime.timedelta
object. To get the original scalar you can use dt.item()
. To index the array scalar you can use the somewhat bizarre syntax of getitem using an empty tuple:
>>> dt[()]
array(datetime.timedelta(0, 65), dtype='timedelta64[s]')
This should work in all versions of numpy, but if you are using numpy v1.7+ it may be better to use the newer numpy datetime API directly as explained in the answer from J.F. Sebastien here. How to convert numpy.timedelta64 to minutes
Use array.astype()
to convert the type of an array safely:
>>> import numpy as np
>>> a = np.timedelta64(1620000000000,'ns')
>>> a.astype('timedelta64[m]')
numpy.timedelta64(27,'m')
How to work with `numpy.timedelta64` outside of pandas/numpy?
When working with datetime64
dtype arrays, tolist()
or item()
do a good job of converting the array to base Python objects. Let's try that with your timedelta:
In [174]: x=np.timedelta64(-2700000000000,'ns')
In [175]: x.item()
Out[175]: -2700000000000
Not quite what we want. But if I first convert it to minutes:In [176]: x.astype('timedelta64[m]')
Out[176]: numpy.timedelta64(-45,'m')
In [177]: x.astype('timedelta64[m]').item()
Out[177]: datetime.timedelta(days=-1, seconds=83700)
getting seconds from numpy timedelta64
Your own answer is correct and good. Slightly different way is to specify scale constants with timedelta
expression.
For example, to scale to seconds:
>>> np.diff(index)/np.timedelta64(1, 's')
array([ 3.6139351 , 3.39279693, 1.87199821])
To minutes:>>> np.diff(index)/np.timedelta64(1, 'm')
array([ 0.06023225, 0.05654662, 0.03119997])
Get year, month or day from numpy datetime64
As datetime is not stable in numpy I would use pandas for this:
In [52]: import pandas as pd
In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])
In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)
Pandas uses numpy datetime internally, but seems to avoid the shortages, that numpy has up to now.
Related Topics
Mapping a Range of Values to Another
Using Configparser to Read a File Without Section Name
Cartesian Product of a Dictionary of Lists
Syntaxerror: Unexpected Eof While Parsing
Generating PDF-Latex with Python Script
How to Pipe Input to Python Line by Line from Linux Program
Subclassing Python Dictionary to Override _Setitem_
How to Ignore One Single Specific Line with Pylint
Why Does Python Use 'Magic Methods'
How to Convert an Int to a Hex String
How to Assign the Same Value to Multiple Keys in a Dict Object at Once
How to Convert Datetime.Timedelta to Minutes, Hours in Python
When to Use Get, Get_Queryset, Get_Context_Data in Django
Python, Remove All Non-Alphabet Chars from String
Handling of Duplicate Indices in Numpy Assignments
Spark Dataframe: Computing Row-Wise Mean (Or Any Aggregate Operation)