Suppose I have a Pandas Series that contains TimeDelta data. In fact it has been generated by taking the difference of a DateTimeIndex with a shifted version of itself, hence giving the delta between consecutive timestamps.
It looks something like
timestamp
2015-02-01 00:00:04 00:00:04
2015-02-01 00:00:08 00:00:04
2015-02-01 00:00:12 00:00:04
....
Name: timestamp, dtype: timedelta64[ns]
The values are obviously numpy.timedelta64 but I need to get them into seconds. There have been similar questions asked relating to this but no answers I have seen yet that deals with Pandas 0.16.1.
What I've tried is:
ts.apply(lambda x: x.seconds)
Which gives an error of
AttributeError: 'numpy.timedelta64' object has no attribute 'seconds'
Then tried
numpy.int64(ts)
But that gives me an array. Now I know I can convert that back into a Series but is there not another way to do this in one Pandas call or mapping function?
The following worked for me:
In [24]:
t="""index,timestamp
2015-02-01 00:00:04,00:00:04
2015-02-01 00:00:08,00:00:04
2015-02-01 00:00:12,00:00:04"""
s = pd.read_csv(io.StringIO(t),parse_dates=[0,1], squeeze=True, index_col=[0])
In [26]:
s.dt.second
Out[26]:
index
2015-02-01 00:00:04 4
2015-02-01 00:00:08 4
2015-02-01 00:00:12 4
dtype: int64
datetime dtype values have a dt
accessor where you can access the seconds attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With