Skip to content

Instantly share code, notes, and snippets.

@MichaelStetner
Created October 31, 2017 20:29
Show Gist options
  • Save MichaelStetner/47b9b7873b23277c900c172373357c70 to your computer and use it in GitHub Desktop.
Save MichaelStetner/47b9b7873b23277c900c172373357c70 to your computer and use it in GitHub Desktop.
Convert any timedelta to seconds
def total_seconds(timedelta):
"""Convert timedeltas to seconds
In Python, time differences can take many formats. This function can take
timedeltas in any format and return the corresponding number of seconds, as
a float.
Beware! Representing timedeltas as floats is not as precise as representing
them as a timedelta object in datetime, numpy, or pandas.
Parameters
----------
timedelta : various
Time delta from python's datetime library or from numpy or pandas. If
it is from numpy, it can be an ndarray with dtype datetime64. If it is
from pandas, it can also be a Series of datetimes. However, this
function cannot operate on entire pandas DataFrames. To convert a
DataFrame, do df.apply(to_seconds)
Returns
-------
seconds : various
Returns the total seconds in the input timedelta object(s) as float.
If the input is a numpy ndarray or pandas Series, the output is the
same, but with a float datatype.
"""
try:
seconds = timedelta.total_seconds()
except AttributeError: # no method total_seconds
one_second = np.timedelta64(1000000000, 'ns')
# use nanoseconds to get highest possible precision in output
seconds = timedelta / one_second
return seconds
@joaofig
Copy link

joaofig commented Oct 14, 2018

You just saved my day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment