时间增量(Timedeltas)

The Timedeltas docs.

Using timedeltas

  1. In [175]: s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
  2. In [176]: s - s.max()
  3. Out[176]:
  4. 0 -2 days
  5. 1 -1 days
  6. 2 0 days
  7. dtype: timedelta64[ns]
  8. In [177]: s.max() - s
  9. Out[177]:
  10. 0 2 days
  11. 1 1 days
  12. 2 0 days
  13. dtype: timedelta64[ns]
  14. In [178]: s - datetime.datetime(2011,1,1,3,5)
  15. Out[178]:
  16. 0 364 days 20:55:00
  17. 1 365 days 20:55:00
  18. 2 366 days 20:55:00
  19. dtype: timedelta64[ns]
  20. In [179]: s + datetime.timedelta(minutes=5)
  21. Out[179]:
  22. 0 2012-01-01 00:05:00
  23. 1 2012-01-02 00:05:00
  24. 2 2012-01-03 00:05:00
  25. dtype: datetime64[ns]
  26. In [180]: datetime.datetime(2011,1,1,3,5) - s
  27. Out[180]:
  28. 0 -365 days +03:05:00
  29. 1 -366 days +03:05:00
  30. 2 -367 days +03:05:00
  31. dtype: timedelta64[ns]
  32. In [181]: datetime.timedelta(minutes=5) + s
  33. Out[181]:
  34. 0 2012-01-01 00:05:00
  35. 1 2012-01-02 00:05:00
  36. 2 2012-01-03 00:05:00
  37. dtype: datetime64[ns]

Adding and subtracting deltas and dates

  1. In [182]: deltas = pd.Series([ datetime.timedelta(days=i) for i in range(3) ])
  2. In [183]: df = pd.DataFrame(dict(A = s, B = deltas)); df
  3. Out[183]:
  4. A B
  5. 0 2012-01-01 0 days
  6. 1 2012-01-02 1 days
  7. 2 2012-01-03 2 days
  8. In [184]: df['New Dates'] = df['A'] + df['B'];
  9. In [185]: df['Delta'] = df['A'] - df['New Dates']; df
  10. Out[185]:
  11. A B New Dates Delta
  12. 0 2012-01-01 0 days 2012-01-01 0 days
  13. 1 2012-01-02 1 days 2012-01-03 -1 days
  14. 2 2012-01-03 2 days 2012-01-05 -2 days
  15. In [186]: df.dtypes
  16. Out[186]:
  17. A datetime64[ns]
  18. B timedelta64[ns]
  19. New Dates datetime64[ns]
  20. Delta timedelta64[ns]
  21. dtype: object

Another example

Values can be set to NaT using np.nan, similar to datetime

  1. In [187]: y = s - s.shift(); y
  2. Out[187]:
  3. 0 NaT
  4. 1 1 days
  5. 2 1 days
  6. dtype: timedelta64[ns]
  7. In [188]: y[1] = np.nan; y
  8. Out[188]:
  9. 0 NaT
  10. 1 NaT
  11. 2 1 days
  12. dtype: timedelta64[ns]