Convert timedelta to total seconds
Use timedelta.total_seconds()
.
>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0
convert timedelta to seconds
You should be able to use the total_seconds method. However, you'd need to access that method via the datetime accessor dt
.
>>> df['duration'].dt.total_seconds()
However, if series Duration
are strings/object- you should do use pd.to_timedelta
>>> pd.to_timedelta(df['duration']).dt.total_seconds()
Python timedelta seconds vs total_seconds
seconds
is the number of seconds within a day, which is in [0, 86399]. total_seconds
is the entire timedelta converted to seconds, and can be any value, for example 604800.0 for one week, or 0.1 for 100 milliseconds.
Convert pandas timedelta to be displayed in seconds
Use the total_seconds()
method on the dt
accessor:
foo['DURATION_NEW'].dt.total_seconds()
Obtaining total seconds from a datetime.time object
You can combine the time with a reference date to get a datetime object. If you then subtract that reference date, you get a timedelta object, from which you can take the total_seconds
:
from datetime import datetime, time
t = time(2,0,0)
ts = (datetime.combine(datetime.min, t) - datetime.min).total_seconds()
print(ts)
# 7200.0
With pandas
, I'd use the string representation of the time object column (Series) and convert it to timedelta datatype - which then allows you to use the dt
accessor to get the total seconds:
import pandas as pd
df = pd.DataFrame({'time': [time(2,0,0)]})
df['totalseconds'] = pd.to_timedelta(df['time'].astype(str)).dt.total_seconds()
# df['totalseconds']
# 0 7200.0
# Name: totalseconds, dtype: float64
Getting the total seconds from a time_delta column python
When you wrote ck = pd.to_timedelta(data['col1'], unit='ns')
your ck
no longer have original col1
, as you write "to create another column" I assume you want to add new columns, then you could use below code:
After your data = pd.read_csv(...
:
data['td'] = pd.to_timedelta(data['col1'], unit='ns')
data['secs'] = data['td'].dt.seconds
will give your something like:
col1 td secs
0 7291413234 00:00:07.291413 7
1 3245345223423 00:54:05.345223 3245
Tested on Jupyter notebook with:
import pandas as pd
import io
temp2=u"""col1
7291413234
3245345223423
"""
data = pd.read_csv(io.StringIO(temp2),sep='\t' , engine='python')
data['td'] = pd.to_timedelta(data['col1'], unit='ns')
data['secs'] = data['td'].dt.seconds
data
Note:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.seconds.html#pandas-series-dt-seconds
Number of seconds (>= 0 and less than 1 day) for each element.
ADDED after comment: total_seconds will return float:
data['secs2'] = data['td'].dt.total_seconds()
data
col1 td secs secs2
0 7291413234 00:00:07.291413 7 7.291413
1 3245345223423 00:54:05.345223 3245 3245.345223
How to extract seconds from datetime.timedelta
Just change
date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
To
date = [(datetime.datetime.strptime(i, format_string)-now).seconds for i in date]date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
convert timedelta hh:mm to seconds
Just append :00
to the end of the string to convert it in the format hh:mm:ss
.
Ex: 08:00
could be rewritten as 08:00:00
Quick way to fix this:
d['A'] = [x + ':00' for x in d['A']]
And then, you can run the following:
secs = (pd.to_timedelta(d['A']).dt.total_seconds())
Related Topics
Type Object 'Datetime.Datetime' Has No Attribute 'Datetime'
Finding the Consecutive Zeros in a Numpy Array
Builtin Function Not Working with Spyder
Why Do Many Examples Use 'Fig, Ax = Plt.Subplots()' in Matplotlib/Pyplot/Python
How to Access a File's Properties on Windows
How to Compare Two JSON Objects with the Same Elements in a Different Order Equal
Typeerror: List Indices Must Be Integers or Slices, Not Str
Accessing a Value in a Tuple That Is in a List
Difference Between the Built-In Pow() and Math.Pow() for Floats, in Python
How to Use Win32 API with Python
Types That Define '_Eq_' Are Unhashable
Sphinx's Autodoc's Automodule Having Apparently No Effect
How to Use a Conditional Expression (Expression with If and Else) in a List Comprehension
Python Requests.Get() Returns Improperly Decoded Text Instead of Utf-8
How to Remove the Top and Right Axis in Matplotlib