4

Consider the following series:

> df['time_delta']

0   -1 days +00:08:11
1     0 days 01:57:46
2     0 days 00:58:34
3     0 days 17:30:23
4   -1 days +21:44:34
5   -2 days +22:01:56
6     0 days 03:18:57
7   -1 days +21:44:48
8   -1 days +00:07:56
Name: time_delta, dtype: timedelta64[ns]

Say I want to convert this timedelta to total signed seconds. That is:

  • Positive deltas should convert to positive seconds
  • Negative deltas should convert to negative seconds

For example:

  • 0 days 00:01:05 => 65 seconds
  • -1 days +23:58:30 => -90 seconds

How can I get this conversion?


Failed attempt

When I try the usual:

temp_df['seconds'] = temp_df['time_delta'].dt.seconds

I end up with:

         time_delta  seconds
0 -1 days +00:08:11      491
1   0 days 01:57:46     7066
2   0 days 00:58:34     3514
3   0 days 17:30:23    63023
4 -1 days +21:44:34    78274
5 -2 days +22:01:56    79316
6   0 days 03:18:57    11937
7 -1 days +21:44:48    78288
8 -1 days +00:07:56      476

which correctly handled positive deltas, but not the negative ones. To see this, note that the negative deltas seem to ignore the sign of the day offset. That is, in the example above:

  • -1 days +21:44:48 should convert to -8112 seconds, not 78288 seconds (wrong sign and value).

2 Answers 2

4

If it's a Timedelta object, just divide it by Timedelta(seconds=1):

>>> pd.Timedelta(days=-1) / pd.Timedelta(seconds=1)
-86400.0
5
  • You'd still need to get rid of the -ve sign though so won't you need to call abs on this anyway?
    – EdChum
    Jan 27, 2016 at 23:33
  • Great solution. This works right away without having to handle signs in a separate step. Jan 27, 2016 at 23:33
  • @EdChum I see your point. To me this seems simpler (it doesn't require knowing dt and total_seconds). Eyes of the beholder, I guess. I'm usually a huge fan of your answers.
    – Ami Tavory
    Jan 27, 2016 at 23:35
  • 1
    FYI, the reason .seconds gives that answer in the OP question is because its a sub-class of datetime.timedelta : docs.python.org/2/library/datetime.html#timedelta-objects, its the seconds of the object, NOT the total_seconds.
    – Jeff
    Jan 28, 2016 at 1:23
  • Thanks, @Jeff - that was my understanding too when I answered this.
    – Ami Tavory
    Jan 28, 2016 at 7:27
2

just call abs prior to dt.total_seconds to get the absolute values:

df['seconds'] = df['time_delta'].abs().dt.total_seconds()

Example:

In [63]:
df = pd.DataFrame({'date_time':pd.date_range(dt.datetime(2015,1,1,12,10,32), dt.datetime(2015,1,3,12,12,30,2))})
df['time_delta'] = df['date_time'] - dt.datetime(2015,1,2)
df

Out[63]:
            date_time        time_delta
0 2015-01-01 12:10:32 -1 days +12:10:32
1 2015-01-02 12:10:32   0 days 12:10:32
2 2015-01-03 12:10:32   1 days 12:10:32

In [64]:    
df['time_delta'].abs().dt.total_seconds()

Out[64]:
0     42568
1     43832
2    130232
Name: time_delta, dtype: float64

To add the signs back you can compare against pd.Timedelta(0):

In [78]:
df['seconds'] = df['time_delta'].abs().dt.total_seconds()
df.loc[df['time_delta'] < pd.Timedelta(0), 'seconds'] = -df['seconds']
df

Out[78]:
            date_time        time_delta  seconds
0 2015-01-01 12:10:32 -1 days +12:10:32   -42568
1 2015-01-02 12:10:32   0 days 12:10:32    43832
2 2015-01-03 12:10:32   1 days 12:10:32   130232

However, I think @Ami Tamory's answer is superior

EDIT After sleeping on this I realised that this is just dt.total_seconds:

In [137]:
df['time_delta'].dt.total_seconds()

Out[137]:
0    -42568
1     43832
2    130232
Name: time_delta, dtype: float64
3
  • Thanks. Good to know. I noticed that sign indexing didn't work right away in other cases (e.g. see this other Q), but it's good to know with abs(). For completeness, to get exactly what I am looking for with your answer, I think I can later change the sign of the result of using abs based on whether or not the original value is above or below than pd.Timedelta(0) as in this other Q. Jan 27, 2016 at 23:28
  • 1
    Yes originally I thought I was going to need to do something like that but then thought won't just abs work and it did so it's simpler
    – EdChum
    Jan 27, 2016 at 23:31
  • 1
    @EdChum I think it can be done in a shorter way (my answer below).
    – Ami Tavory
    Jan 27, 2016 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.