Time series / date functionality

pandas contains extensive capabilities and features for working with time series data for all domains.Using the NumPy datetime64 and timedelta64 dtypes, pandas has consolidated a large number offeatures from other Python libraries like scikits.timeseries as well as createda tremendous amount of new functionality for manipulating time series data.

For example, pandas supports:

Parsing time series information from various sources and formats

  1. In [1]: import datetime
  2.  
  3. In [2]: dti = pd.to_datetime(['1/1/2018', np.datetime64('2018-01-01'),
  4. ...: datetime.datetime(2018, 1, 1)])
  5. ...:
  6.  
  7. In [3]: dti
  8. Out[3]: DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01'], dtype='datetime64[ns]', freq=None)

Generate sequences of fixed-frequency dates and time spans

  1. In [4]: dti = pd.date_range('2018-01-01', periods=3, freq='H')
  2.  
  3. In [5]: dti
  4. Out[5]:
  5. DatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 01:00:00',
  6. '2018-01-01 02:00:00'],
  7. dtype='datetime64[ns]', freq='H')

Manipulating and converting date times with timezone information

  1. In [6]: dti = dti.tz_localize('UTC')
  2.  
  3. In [7]: dti
  4. Out[7]:
  5. DatetimeIndex(['2018-01-01 00:00:00+00:00', '2018-01-01 01:00:00+00:00',
  6. '2018-01-01 02:00:00+00:00'],
  7. dtype='datetime64[ns, UTC]', freq='H')
  8.  
  9. In [8]: dti.tz_convert('US/Pacific')
  10. Out[8]:
  11. DatetimeIndex(['2017-12-31 16:00:00-08:00', '2017-12-31 17:00:00-08:00',
  12. '2017-12-31 18:00:00-08:00'],
  13. dtype='datetime64[ns, US/Pacific]', freq='H')

Resampling or converting a time series to a particular frequency

  1. In [9]: idx = pd.date_range('2018-01-01', periods=5, freq='H')
  2.  
  3. In [10]: ts = pd.Series(range(len(idx)), index=idx)
  4.  
  5. In [11]: ts
  6. Out[11]:
  7. 2018-01-01 00:00:00 0
  8. 2018-01-01 01:00:00 1
  9. 2018-01-01 02:00:00 2
  10. 2018-01-01 03:00:00 3
  11. 2018-01-01 04:00:00 4
  12. Freq: H, dtype: int64
  13.  
  14. In [12]: ts.resample('2H').mean()
  15. Out[12]:
  16. 2018-01-01 00:00:00 0.5
  17. 2018-01-01 02:00:00 2.5
  18. 2018-01-01 04:00:00 4.0
  19. Freq: 2H, dtype: float64

Performing date and time arithmetic with absolute or relative time increments

  1. In [13]: friday = pd.Timestamp('2018-01-05')
  2.  
  3. In [14]: friday.day_name()
  4. Out[14]: 'Friday'
  5.  
  6. # Add 1 day
  7. In [15]: saturday = friday + pd.Timedelta('1 day')
  8.  
  9. In [16]: saturday.day_name()
  10. Out[16]: 'Saturday'
  11.  
  12. # Add 1 business day (Friday --> Monday)
  13. In [17]: monday = friday + pd.offsets.BDay()
  14.  
  15. In [18]: monday.day_name()
  16. Out[18]: 'Monday'

pandas provides a relatively compact and self-contained set of tools forperforming the above tasks and more.

Overview

pandas captures 4 general time related concepts:

  • Date times: A specific date and time with timezone support. Similar to datetime.datetime from the standard library.
  • Time deltas: An absolute time duration. Similar to datetime.timedelta from the standard library.
  • Time spans: A span of time defined by a point in time and its associated frequency.
  • Date offsets: A relative time duration that respects calendar arithmetic. Similar to dateutil.relativedelta.relativedelta from the dateutil package.
ConceptScalar ClassArray Classpandas Data TypePrimary Creation Method
Date timesTimestampDatetimeIndexdatetime64[ns] or datetime64[ns, tz]to_datetime or date_range
Time deltasTimedeltaTimedeltaIndextimedelta64[ns]to_timedelta or timedelta_range
Time spansPeriodPeriodIndexperiod[freq]Period or period_range
Date offsetsDateOffsetNoneNoneDateOffset

For time series data, it’s conventional to represent the time component in the index of a Series or DataFrameso manipulations can be performed with respect to the time element.

  1. In [19]: pd.Series(range(3), index=pd.date_range('2000', freq='D', periods=3))
  2. Out[19]:
  3. 2000-01-01 0
  4. 2000-01-02 1
  5. 2000-01-03 2
  6. Freq: D, dtype: int64

However, Series and DataFrame can directly also support the time component as data itself.

  1. In [20]: pd.Series(pd.date_range('2000', freq='D', periods=3))
  2. Out[20]:
  3. 0 2000-01-01
  4. 1 2000-01-02
  5. 2 2000-01-03
  6. dtype: datetime64[ns]

Series and DataFrame have extended data type support and functionality for datetime, timedeltaand Period data when passed into those constructors. DateOffsetdata however will be stored as object data.

  1. In [21]: pd.Series(pd.period_range('1/1/2011', freq='M', periods=3))
  2. Out[21]:
  3. 0 2011-01
  4. 1 2011-02
  5. 2 2011-03
  6. dtype: period[M]
  7.  
  8. In [22]: pd.Series([pd.DateOffset(1), pd.DateOffset(2)])
  9. Out[22]:
  10. 0 <DateOffset>
  11. 1 <2 * DateOffsets>
  12. dtype: object
  13.  
  14. In [23]: pd.Series(pd.date_range('1/1/2011', freq='M', periods=3))
  15. Out[23]:
  16. 0 2011-01-31
  17. 1 2011-02-28
  18. 2 2011-03-31
  19. dtype: datetime64[ns]

Lastly, pandas represents null date times, time deltas, and time spans as NaT whichis useful for representing missing or null date like values and behaves similaras np.nan does for float data.

  1. In [24]: pd.Timestamp(pd.NaT)
  2. Out[24]: NaT
  3.  
  4. In [25]: pd.Timedelta(pd.NaT)
  5. Out[25]: NaT
  6.  
  7. In [26]: pd.Period(pd.NaT)
  8. Out[26]: NaT
  9.  
  10. # Equality acts as np.nan would
  11. In [27]: pd.NaT == pd.NaT
  12. Out[27]: False

Timestamps vs. Time Spans

Timestamped data is the most basic type of time series data that associatesvalues with points in time. For pandas objects it means using the points intime.

  1. In [28]: pd.Timestamp(datetime.datetime(2012, 5, 1))
  2. Out[28]: Timestamp('2012-05-01 00:00:00')
  3.  
  4. In [29]: pd.Timestamp('2012-05-01')
  5. Out[29]: Timestamp('2012-05-01 00:00:00')
  6.  
  7. In [30]: pd.Timestamp(2012, 5, 1)
  8. Out[30]: Timestamp('2012-05-01 00:00:00')

However, in many cases it is more natural to associate things like changevariables with a time span instead. The span represented by Period can bespecified explicitly, or inferred from datetime string format.

For example:

  1. In [31]: pd.Period('2011-01')
  2. Out[31]: Period('2011-01', 'M')
  3.  
  4. In [32]: pd.Period('2012-05', freq='D')
  5. Out[32]: Period('2012-05-01', 'D')

Timestamp and Period can serve as an index. Lists ofTimestamp and Period are automatically coerced to DatetimeIndexand PeriodIndex respectively.

  1. In [33]: dates = [pd.Timestamp('2012-05-01'),
  2. ....: pd.Timestamp('2012-05-02'),
  3. ....: pd.Timestamp('2012-05-03')]
  4. ....:
  5.  
  6. In [34]: ts = pd.Series(np.random.randn(3), dates)
  7.  
  8. In [35]: type(ts.index)
  9. Out[35]: pandas.core.indexes.datetimes.DatetimeIndex
  10.  
  11. In [36]: ts.index
  12. Out[36]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)
  13.  
  14. In [37]: ts
  15. Out[37]:
  16. 2012-05-01 0.469112
  17. 2012-05-02 -0.282863
  18. 2012-05-03 -1.509059
  19. dtype: float64
  20.  
  21. In [38]: periods = [pd.Period('2012-01'), pd.Period('2012-02'), pd.Period('2012-03')]
  22.  
  23. In [39]: ts = pd.Series(np.random.randn(3), periods)
  24.  
  25. In [40]: type(ts.index)
  26. Out[40]: pandas.core.indexes.period.PeriodIndex
  27.  
  28. In [41]: ts.index
  29. Out[41]: PeriodIndex(['2012-01', '2012-02', '2012-03'], dtype='period[M]', freq='M')
  30.  
  31. In [42]: ts
  32. Out[42]:
  33. 2012-01 -1.135632
  34. 2012-02 1.212112
  35. 2012-03 -0.173215
  36. Freq: M, dtype: float64

pandas allows you to capture both representations andconvert between them. Under the hood, pandas represents timestamps usinginstances of Timestamp and sequences of timestamps using instances ofDatetimeIndex. For regular time spans, pandas uses Period objects forscalar values and PeriodIndex for sequences of spans. Better support forirregular intervals with arbitrary start and end points are forth-coming infuture releases.

Converting to timestamps

To convert a Series or list-like object of date-like objects e.g. strings,epochs, or a mixture, you can use the to_datetime function. When passeda Series, this returns a Series (with the same index), while a list-likeis converted to a DatetimeIndex:

  1. In [43]: pd.to_datetime(pd.Series(['Jul 31, 2009', '2010-01-10', None]))
  2. Out[43]:
  3. 0 2009-07-31
  4. 1 2010-01-10
  5. 2 NaT
  6. dtype: datetime64[ns]
  7.  
  8. In [44]: pd.to_datetime(['2005/11/23', '2010.12.31'])
  9. Out[44]: DatetimeIndex(['2005-11-23', '2010-12-31'], dtype='datetime64[ns]', freq=None)

If you use dates which start with the day first (i.e. European style),you can pass the dayfirst flag:

  1. In [45]: pd.to_datetime(['04-01-2012 10:00'], dayfirst=True)
  2. Out[45]: DatetimeIndex(['2012-01-04 10:00:00'], dtype='datetime64[ns]', freq=None)
  3.  
  4. In [46]: pd.to_datetime(['14-01-2012', '01-14-2012'], dayfirst=True)
  5. Out[46]: DatetimeIndex(['2012-01-14', '2012-01-14'], dtype='datetime64[ns]', freq=None)

Warning

You see in the above example that dayfirst isn’t strict, so if a datecan’t be parsed with the day being first it will be parsed as ifdayfirst were False.

If you pass a single string to to_datetime, it returns a single Timestamp.Timestamp can also accept string input, but it doesn’t accept string parsingoptions like dayfirst or format, so use to_datetime if these are required.

  1. In [47]: pd.to_datetime('2010/11/12')
  2. Out[47]: Timestamp('2010-11-12 00:00:00')
  3.  
  4. In [48]: pd.Timestamp('2010/11/12')
  5. Out[48]: Timestamp('2010-11-12 00:00:00')

You can also use the DatetimeIndex constructor directly:

  1. In [49]: pd.DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'])
  2. Out[49]: DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], dtype='datetime64[ns]', freq=None)

The string ‘infer’ can be passed in order to set the frequency of the index as theinferred frequency upon creation:

  1. In [50]: pd.DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], freq='infer')
  2. Out[50]: DatetimeIndex(['2018-01-01', '2018-01-03', '2018-01-05'], dtype='datetime64[ns]', freq='2D')

Providing a format argument

In addition to the required datetime string, a format argument can be passed to ensure specific parsing.This could also potentially speed up the conversion considerably.

  1. In [51]: pd.to_datetime('2010/11/12', format='%Y/%m/%d')
  2. Out[51]: Timestamp('2010-11-12 00:00:00')
  3.  
  4. In [52]: pd.to_datetime('12-11-2010 00:00', format='%d-%m-%Y %H:%M')
  5. Out[52]: Timestamp('2010-11-12 00:00:00')

For more information on the choices available when specifying the formatoption, see the Python datetime documentation.

Assembling datetime from multiple DataFrame columns

New in version 0.18.1.

You can also pass a DataFrame of integer or string columns to assemble into a Series of Timestamps.

  1. In [53]: df = pd.DataFrame({'year': [2015, 2016],
  2. ....: 'month': [2, 3],
  3. ....: 'day': [4, 5],
  4. ....: 'hour': [2, 3]})
  5. ....:
  6.  
  7. In [54]: pd.to_datetime(df)
  8. Out[54]:
  9. 0 2015-02-04 02:00:00
  10. 1 2016-03-05 03:00:00
  11. dtype: datetime64[ns]

You can pass only the columns that you need to assemble.

  1. In [55]: pd.to_datetime(df[['year', 'month', 'day']])
  2. Out[55]:
  3. 0 2015-02-04
  4. 1 2016-03-05
  5. dtype: datetime64[ns]

pd.to_datetime looks for standard designations of the datetime component in the column names, including:

  • required: year, month, day
  • optional: hour, minute, second, millisecond, microsecond, nanosecond

Invalid data

The default behavior, errors='raise', is to raise when unparseable:

  1. In [2]: pd.to_datetime(['2009/07/31', 'asd'], errors='raise')
  2. ValueError: Unknown string format

Pass errors='ignore' to return the original input when unparseable:

  1. In [56]: pd.to_datetime(['2009/07/31', 'asd'], errors='ignore')
  2. Out[56]: Index(['2009/07/31', 'asd'], dtype='object')

Pass errors='coerce' to convert unparseable data to NaT (not a time):

  1. In [57]: pd.to_datetime(['2009/07/31', 'asd'], errors='coerce')
  2. Out[57]: DatetimeIndex(['2009-07-31', 'NaT'], dtype='datetime64[ns]', freq=None)

Epoch timestamps

pandas supports converting integer or float epoch times to Timestamp andDatetimeIndex. The default unit is nanoseconds, since that is how Timestampobjects are stored internally. However, epochs are often stored in another unitwhich can be specified. These are computed from the starting point specified by theorigin parameter.

  1. In [58]: pd.to_datetime([1349720105, 1349806505, 1349892905,
  2. ....: 1349979305, 1350065705], unit='s')
  3. ....:
  4. Out[58]:
  5. DatetimeIndex(['2012-10-08 18:15:05', '2012-10-09 18:15:05',
  6. '2012-10-10 18:15:05', '2012-10-11 18:15:05',
  7. '2012-10-12 18:15:05'],
  8. dtype='datetime64[ns]', freq=None)
  9.  
  10. In [59]: pd.to_datetime([1349720105100, 1349720105200, 1349720105300,
  11. ....: 1349720105400, 1349720105500], unit='ms')
  12. ....:
  13. Out[59]:
  14. DatetimeIndex(['2012-10-08 18:15:05.100000', '2012-10-08 18:15:05.200000',
  15. '2012-10-08 18:15:05.300000', '2012-10-08 18:15:05.400000',
  16. '2012-10-08 18:15:05.500000'],
  17. dtype='datetime64[ns]', freq=None)

Constructing a Timestamp or DatetimeIndex with an epoch timestampwith the tz argument specified will currently localize the epoch timestamps to UTCfirst then convert the result to the specified time zone. However, this behavioris deprecated, and if you haveepochs in wall time in another timezone, it is recommended to read the epochsas timezone-naive timestamps and then localize to the appropriate timezone:

  1. In [60]: pd.Timestamp(1262347200000000000).tz_localize('US/Pacific')
  2. Out[60]: Timestamp('2010-01-01 12:00:00-0800', tz='US/Pacific')
  3.  
  4. In [61]: pd.DatetimeIndex([1262347200000000000]).tz_localize('US/Pacific')
  5. Out[61]: DatetimeIndex(['2010-01-01 12:00:00-08:00'], dtype='datetime64[ns, US/Pacific]', freq=None)

Note

Epoch times will be rounded to the nearest nanosecond.

Warning

Conversion of float epoch times can lead to inaccurate and unexpected results.Python floats have about 15 digits precision indecimal. Rounding during conversion from float to high precision Timestamp isunavoidable. The only way to achieve exact precision is to use a fixed-widthtypes (e.g. an int64).

  1. In [62]: pd.to_datetime([1490195805.433, 1490195805.433502912], unit='s')
  2. Out[62]: DatetimeIndex(['2017-03-22 15:16:45.433000088', '2017-03-22 15:16:45.433502913'], dtype='datetime64[ns]', freq=None)
  3.  
  4. In [63]: pd.to_datetime(1490195805433502912, unit='ns')
  5. Out[63]: Timestamp('2017-03-22 15:16:45.433502912')

See also

Using the origin Parameter

From timestamps to epoch

To invert the operation from above, namely, to convert from a Timestamp to a ‘unix’ epoch:

  1. In [64]: stamps = pd.date_range('2012-10-08 18:15:05', periods=4, freq='D')
  2.  
  3. In [65]: stamps
  4. Out[65]:
  5. DatetimeIndex(['2012-10-08 18:15:05', '2012-10-09 18:15:05',
  6. '2012-10-10 18:15:05', '2012-10-11 18:15:05'],
  7. dtype='datetime64[ns]', freq='D')

We subtract the epoch (midnight at January 1, 1970 UTC) and then floor divide by the“unit” (1 second).

  1. In [66]: (stamps - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
  2. Out[66]: Int64Index([1349720105, 1349806505, 1349892905, 1349979305], dtype='int64')

Using the origin Parameter

New in version 0.20.0.

Using the origin parameter, one can specify an alternative starting point for creationof a DatetimeIndex. For example, to use 1960-01-01 as the starting date:

  1. In [67]: pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01'))
  2. Out[67]: DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None)

The default is set at origin='unix', which defaults to 1970-01-01 00:00:00.Commonly called ‘unix epoch’ or POSIX time.

  1. In [68]: pd.to_datetime([1, 2, 3], unit='D')
  2. Out[68]: DatetimeIndex(['1970-01-02', '1970-01-03', '1970-01-04'], dtype='datetime64[ns]', freq=None)

Generating ranges of timestamps

To generate an index with timestamps, you can use either the DatetimeIndex orIndex constructor and pass in a list of datetime objects:

  1. In [69]: dates = [datetime.datetime(2012, 5, 1),
  2. ....: datetime.datetime(2012, 5, 2),
  3. ....: datetime.datetime(2012, 5, 3)]
  4. ....:
  5.  
  6. # Note the frequency information
  7. In [70]: index = pd.DatetimeIndex(dates)
  8.  
  9. In [71]: index
  10. Out[71]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)
  11.  
  12. # Automatically converted to DatetimeIndex
  13. In [72]: index = pd.Index(dates)
  14.  
  15. In [73]: index
  16. Out[73]: DatetimeIndex(['2012-05-01', '2012-05-02', '2012-05-03'], dtype='datetime64[ns]', freq=None)

In practice this becomes very cumbersome because we often need a very longindex with a large number of timestamps. If we need timestamps on a regularfrequency, we can use the date_range() and bdate_range() functionsto create a DatetimeIndex. The default frequency for date_range is acalendar day while the default for bdate_range is a business day:

  1. In [74]: start = datetime.datetime(2011, 1, 1)
  2.  
  3. In [75]: end = datetime.datetime(2012, 1, 1)
  4.  
  5. In [76]: index = pd.date_range(start, end)
  6.  
  7. In [77]: index
  8. Out[77]:
  9. DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04',
  10. '2011-01-05', '2011-01-06', '2011-01-07', '2011-01-08',
  11. '2011-01-09', '2011-01-10',
  12. ...
  13. '2011-12-23', '2011-12-24', '2011-12-25', '2011-12-26',
  14. '2011-12-27', '2011-12-28', '2011-12-29', '2011-12-30',
  15. '2011-12-31', '2012-01-01'],
  16. dtype='datetime64[ns]', length=366, freq='D')
  17.  
  18. In [78]: index = pd.bdate_range(start, end)
  19.  
  20. In [79]: index
  21. Out[79]:
  22. DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
  23. '2011-01-07', '2011-01-10', '2011-01-11', '2011-01-12',
  24. '2011-01-13', '2011-01-14',
  25. ...
  26. '2011-12-19', '2011-12-20', '2011-12-21', '2011-12-22',
  27. '2011-12-23', '2011-12-26', '2011-12-27', '2011-12-28',
  28. '2011-12-29', '2011-12-30'],
  29. dtype='datetime64[ns]', length=260, freq='B')

Convenience functions like date_range and bdate_range can utilize avariety of frequency aliases:

  1. In [80]: pd.date_range(start, periods=1000, freq='M')
  2. Out[80]:
  3. DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-30',
  4. '2011-05-31', '2011-06-30', '2011-07-31', '2011-08-31',
  5. '2011-09-30', '2011-10-31',
  6. ...
  7. '2093-07-31', '2093-08-31', '2093-09-30', '2093-10-31',
  8. '2093-11-30', '2093-12-31', '2094-01-31', '2094-02-28',
  9. '2094-03-31', '2094-04-30'],
  10. dtype='datetime64[ns]', length=1000, freq='M')
  11.  
  12. In [81]: pd.bdate_range(start, periods=250, freq='BQS')
  13. Out[81]:
  14. DatetimeIndex(['2011-01-03', '2011-04-01', '2011-07-01', '2011-10-03',
  15. '2012-01-02', '2012-04-02', '2012-07-02', '2012-10-01',
  16. '2013-01-01', '2013-04-01',
  17. ...
  18. '2071-01-01', '2071-04-01', '2071-07-01', '2071-10-01',
  19. '2072-01-01', '2072-04-01', '2072-07-01', '2072-10-03',
  20. '2073-01-02', '2073-04-03'],
  21. dtype='datetime64[ns]', length=250, freq='BQS-JAN')

date_range and bdate_range make it easy to generate a range of datesusing various combinations of parameters like start, end, periods,and freq. The start and end dates are strictly inclusive, so dates outsideof those specified will not be generated:

  1. In [82]: pd.date_range(start, end, freq='BM')
  2. Out[82]:
  3. DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
  4. '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31',
  5. '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'],
  6. dtype='datetime64[ns]', freq='BM')
  7.  
  8. In [83]: pd.date_range(start, end, freq='W')
  9. Out[83]:
  10. DatetimeIndex(['2011-01-02', '2011-01-09', '2011-01-16', '2011-01-23',
  11. '2011-01-30', '2011-02-06', '2011-02-13', '2011-02-20',
  12. '2011-02-27', '2011-03-06', '2011-03-13', '2011-03-20',
  13. '2011-03-27', '2011-04-03', '2011-04-10', '2011-04-17',
  14. '2011-04-24', '2011-05-01', '2011-05-08', '2011-05-15',
  15. '2011-05-22', '2011-05-29', '2011-06-05', '2011-06-12',
  16. '2011-06-19', '2011-06-26', '2011-07-03', '2011-07-10',
  17. '2011-07-17', '2011-07-24', '2011-07-31', '2011-08-07',
  18. '2011-08-14', '2011-08-21', '2011-08-28', '2011-09-04',
  19. '2011-09-11', '2011-09-18', '2011-09-25', '2011-10-02',
  20. '2011-10-09', '2011-10-16', '2011-10-23', '2011-10-30',
  21. '2011-11-06', '2011-11-13', '2011-11-20', '2011-11-27',
  22. '2011-12-04', '2011-12-11', '2011-12-18', '2011-12-25',
  23. '2012-01-01'],
  24. dtype='datetime64[ns]', freq='W-SUN')
  25.  
  26. In [84]: pd.bdate_range(end=end, periods=20)
  27. Out[84]:
  28. DatetimeIndex(['2011-12-05', '2011-12-06', '2011-12-07', '2011-12-08',
  29. '2011-12-09', '2011-12-12', '2011-12-13', '2011-12-14',
  30. '2011-12-15', '2011-12-16', '2011-12-19', '2011-12-20',
  31. '2011-12-21', '2011-12-22', '2011-12-23', '2011-12-26',
  32. '2011-12-27', '2011-12-28', '2011-12-29', '2011-12-30'],
  33. dtype='datetime64[ns]', freq='B')
  34.  
  35. In [85]: pd.bdate_range(start=start, periods=20)
  36. Out[85]:
  37. DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
  38. '2011-01-07', '2011-01-10', '2011-01-11', '2011-01-12',
  39. '2011-01-13', '2011-01-14', '2011-01-17', '2011-01-18',
  40. '2011-01-19', '2011-01-20', '2011-01-21', '2011-01-24',
  41. '2011-01-25', '2011-01-26', '2011-01-27', '2011-01-28'],
  42. dtype='datetime64[ns]', freq='B')

New in version 0.23.0.

Specifying start, end, and periods will generate a range of evenly spaceddates from start to end inclusively, with periods number of elements in theresulting DatetimeIndex:

  1. In [86]: pd.date_range('2018-01-01', '2018-01-05', periods=5)
  2. Out[86]:
  3. DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
  4. '2018-01-05'],
  5. dtype='datetime64[ns]', freq=None)
  6.  
  7. In [87]: pd.date_range('2018-01-01', '2018-01-05', periods=10)
  8. Out[87]:
  9. DatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 10:40:00',
  10. '2018-01-01 21:20:00', '2018-01-02 08:00:00',
  11. '2018-01-02 18:40:00', '2018-01-03 05:20:00',
  12. '2018-01-03 16:00:00', '2018-01-04 02:40:00',
  13. '2018-01-04 13:20:00', '2018-01-05 00:00:00'],
  14. dtype='datetime64[ns]', freq=None)

Custom frequency ranges

bdate_range can also generate a range of custom frequency dates by usingthe weekmask and holidays parameters. These parameters will only beused if a custom frequency string is passed.

  1. In [88]: weekmask = 'Mon Wed Fri'
  2.  
  3. In [89]: holidays = [datetime.datetime(2011, 1, 5), datetime.datetime(2011, 3, 14)]
  4.  
  5. In [90]: pd.bdate_range(start, end, freq='C', weekmask=weekmask, holidays=holidays)
  6. Out[90]:
  7. DatetimeIndex(['2011-01-03', '2011-01-07', '2011-01-10', '2011-01-12',
  8. '2011-01-14', '2011-01-17', '2011-01-19', '2011-01-21',
  9. '2011-01-24', '2011-01-26',
  10. ...
  11. '2011-12-09', '2011-12-12', '2011-12-14', '2011-12-16',
  12. '2011-12-19', '2011-12-21', '2011-12-23', '2011-12-26',
  13. '2011-12-28', '2011-12-30'],
  14. dtype='datetime64[ns]', length=154, freq='C')
  15.  
  16. In [91]: pd.bdate_range(start, end, freq='CBMS', weekmask=weekmask)
  17. Out[91]:
  18. DatetimeIndex(['2011-01-03', '2011-02-02', '2011-03-02', '2011-04-01',
  19. '2011-05-02', '2011-06-01', '2011-07-01', '2011-08-01',
  20. '2011-09-02', '2011-10-03', '2011-11-02', '2011-12-02'],
  21. dtype='datetime64[ns]', freq='CBMS')

See also

Custom business days

Timestamp limitations

Since pandas represents timestamps in nanosecond resolution, the time span thatcan be represented using a 64-bit integer is limited to approximately 584 years:

  1. In [92]: pd.Timestamp.min
  2. Out[92]: Timestamp('1677-09-21 00:12:43.145225')
  3.  
  4. In [93]: pd.Timestamp.max
  5. Out[93]: Timestamp('2262-04-11 23:47:16.854775807')

See also

Representing out-of-bounds spans

Indexing

One of the main uses for DatetimeIndex is as an index for pandas objects.The DatetimeIndex class contains many time series related optimizations:

  • A large range of dates for various offsets are pre-computed and cachedunder the hood in order to make generating subsequent date ranges very fast(just have to grab a slice).
  • Fast shifting using the shift and tshift method on pandas objects.
  • Unioning of overlapping DatetimeIndex objects with the same frequency isvery fast (important for fast data alignment).
  • Quick access to date fields via properties such as year, month, etc.
  • Regularization functions like snap and very fast asof logic.

DatetimeIndex objects have all the basic functionality of regular Indexobjects, and a smorgasbord of advanced time series specific methods for easyfrequency processing.

See also

Reindexing methods

Note

While pandas does not force you to have a sorted date index, some of thesemethods may have unexpected or incorrect behavior if the dates are unsorted.

DatetimeIndex can be used like a regular index and offers all of itsintelligent functionality like selection, slicing, etc.

  1. In [94]: rng = pd.date_range(start, end, freq='BM')
  2.  
  3. In [95]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
  4.  
  5. In [96]: ts.index
  6. Out[96]:
  7. DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
  8. '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31',
  9. '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'],
  10. dtype='datetime64[ns]', freq='BM')
  11.  
  12. In [97]: ts[:5].index
  13. Out[97]:
  14. DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
  15. '2011-05-31'],
  16. dtype='datetime64[ns]', freq='BM')
  17.  
  18. In [98]: ts[::2].index
  19. Out[98]:
  20. DatetimeIndex(['2011-01-31', '2011-03-31', '2011-05-31', '2011-07-29',
  21. '2011-09-30', '2011-11-30'],
  22. dtype='datetime64[ns]', freq='2BM')

Partial string indexing

Dates and strings that parse to timestamps can be passed as indexing parameters:

  1. In [99]: ts['1/31/2011']
  2. Out[99]: 0.11920871129693428
  3.  
  4. In [100]: ts[datetime.datetime(2011, 12, 25):]
  5. Out[100]:
  6. 2011-12-30 0.56702
  7. Freq: BM, dtype: float64
  8.  
  9. In [101]: ts['10/31/2011':'12/31/2011']
  10. Out[101]:
  11. 2011-10-31 0.271860
  12. 2011-11-30 -0.424972
  13. 2011-12-30 0.567020
  14. Freq: BM, dtype: float64

To provide convenience for accessing longer time series, you can also pass inthe year or year and month as strings:

  1. In [102]: ts['2011']
  2. Out[102]:
  3. 2011-01-31 0.119209
  4. 2011-02-28 -1.044236
  5. 2011-03-31 -0.861849
  6. 2011-04-29 -2.104569
  7. 2011-05-31 -0.494929
  8. 2011-06-30 1.071804
  9. 2011-07-29 0.721555
  10. 2011-08-31 -0.706771
  11. 2011-09-30 -1.039575
  12. 2011-10-31 0.271860
  13. 2011-11-30 -0.424972
  14. 2011-12-30 0.567020
  15. Freq: BM, dtype: float64
  16.  
  17. In [103]: ts['2011-6']
  18. Out[103]:
  19. 2011-06-30 1.071804
  20. Freq: BM, dtype: float64

This type of slicing will work on a DataFrame with a DatetimeIndex as well. Since thepartial string selection is a form of label slicing, the endpoints will be included. Thiswould include matching times on an included date:

  1. In [104]: dft = pd.DataFrame(np.random.randn(100000, 1), columns=['A'],
  2. .....: index=pd.date_range('20130101', periods=100000, freq='T'))
  3. .....:
  4.  
  5. In [105]: dft
  6. Out[105]:
  7. A
  8. 2013-01-01 00:00:00 0.276232
  9. 2013-01-01 00:01:00 -1.087401
  10. 2013-01-01 00:02:00 -0.673690
  11. 2013-01-01 00:03:00 0.113648
  12. 2013-01-01 00:04:00 -1.478427
  13. ... ...
  14. 2013-03-11 10:35:00 -0.747967
  15. 2013-03-11 10:36:00 -0.034523
  16. 2013-03-11 10:37:00 -0.201754
  17. 2013-03-11 10:38:00 -1.509067
  18. 2013-03-11 10:39:00 -1.693043
  19.  
  20. [100000 rows x 1 columns]
  21.  
  22. In [106]: dft['2013']
  23. Out[106]:
  24. A
  25. 2013-01-01 00:00:00 0.276232
  26. 2013-01-01 00:01:00 -1.087401
  27. 2013-01-01 00:02:00 -0.673690
  28. 2013-01-01 00:03:00 0.113648
  29. 2013-01-01 00:04:00 -1.478427
  30. ... ...
  31. 2013-03-11 10:35:00 -0.747967
  32. 2013-03-11 10:36:00 -0.034523
  33. 2013-03-11 10:37:00 -0.201754
  34. 2013-03-11 10:38:00 -1.509067
  35. 2013-03-11 10:39:00 -1.693043
  36.  
  37. [100000 rows x 1 columns]

This starts on the very first time in the month, and includes the last date andtime for the month:

  1. In [107]: dft['2013-1':'2013-2']
  2. Out[107]:
  3. A
  4. 2013-01-01 00:00:00 0.276232
  5. 2013-01-01 00:01:00 -1.087401
  6. 2013-01-01 00:02:00 -0.673690
  7. 2013-01-01 00:03:00 0.113648
  8. 2013-01-01 00:04:00 -1.478427
  9. ... ...
  10. 2013-02-28 23:55:00 0.850929
  11. 2013-02-28 23:56:00 0.976712
  12. 2013-02-28 23:57:00 -2.693884
  13. 2013-02-28 23:58:00 -1.575535
  14. 2013-02-28 23:59:00 -1.573517
  15.  
  16. [84960 rows x 1 columns]

This specifies a stop time that includes all of the times on the last day:

  1. In [108]: dft['2013-1':'2013-2-28']
  2. Out[108]:
  3. A
  4. 2013-01-01 00:00:00 0.276232
  5. 2013-01-01 00:01:00 -1.087401
  6. 2013-01-01 00:02:00 -0.673690
  7. 2013-01-01 00:03:00 0.113648
  8. 2013-01-01 00:04:00 -1.478427
  9. ... ...
  10. 2013-02-28 23:55:00 0.850929
  11. 2013-02-28 23:56:00 0.976712
  12. 2013-02-28 23:57:00 -2.693884
  13. 2013-02-28 23:58:00 -1.575535
  14. 2013-02-28 23:59:00 -1.573517
  15.  
  16. [84960 rows x 1 columns]

This specifies an exact stop time (and is not the same as the above):

  1. In [109]: dft['2013-1':'2013-2-28 00:00:00']
  2. Out[109]:
  3. A
  4. 2013-01-01 00:00:00 0.276232
  5. 2013-01-01 00:01:00 -1.087401
  6. 2013-01-01 00:02:00 -0.673690
  7. 2013-01-01 00:03:00 0.113648
  8. 2013-01-01 00:04:00 -1.478427
  9. ... ...
  10. 2013-02-27 23:56:00 1.197749
  11. 2013-02-27 23:57:00 0.720521
  12. 2013-02-27 23:58:00 -0.072718
  13. 2013-02-27 23:59:00 -0.681192
  14. 2013-02-28 00:00:00 -0.557501
  15.  
  16. [83521 rows x 1 columns]

We are stopping on the included end-point as it is part of the index:

  1. In [110]: dft['2013-1-15':'2013-1-15 12:30:00']
  2. Out[110]:
  3. A
  4. 2013-01-15 00:00:00 -0.984810
  5. 2013-01-15 00:01:00 0.941451
  6. 2013-01-15 00:02:00 1.559365
  7. 2013-01-15 00:03:00 1.034374
  8. 2013-01-15 00:04:00 -1.480656
  9. ... ...
  10. 2013-01-15 12:26:00 0.371454
  11. 2013-01-15 12:27:00 -0.930806
  12. 2013-01-15 12:28:00 -0.069177
  13. 2013-01-15 12:29:00 0.066510
  14. 2013-01-15 12:30:00 -0.003945
  15.  
  16. [751 rows x 1 columns]

New in version 0.18.0.

DatetimeIndex partial string indexing also works on a DataFrame with a MultiIndex:

  1. In [111]: dft2 = pd.DataFrame(np.random.randn(20, 1),
  2. .....: columns=['A'],
  3. .....: index=pd.MultiIndex.from_product(
  4. .....: [pd.date_range('20130101', periods=10, freq='12H'),
  5. .....: ['a', 'b']]))
  6. .....:
  7.  
  8. In [112]: dft2
  9. Out[112]:
  10. A
  11. 2013-01-01 00:00:00 a -0.298694
  12. b 0.823553
  13. 2013-01-01 12:00:00 a 0.943285
  14. b -1.479399
  15. 2013-01-02 00:00:00 a -1.643342
  16. ... ...
  17. 2013-01-04 12:00:00 b 0.069036
  18. 2013-01-05 00:00:00 a 0.122297
  19. b 1.422060
  20. 2013-01-05 12:00:00 a 0.370079
  21. b 1.016331
  22.  
  23. [20 rows x 1 columns]
  24.  
  25. In [113]: dft2.loc['2013-01-05']
  26. Out[113]:
  27. A
  28. 2013-01-05 00:00:00 a 0.122297
  29. b 1.422060
  30. 2013-01-05 12:00:00 a 0.370079
  31. b 1.016331
  32.  
  33. In [114]: idx = pd.IndexSlice
  34.  
  35. In [115]: dft2 = dft2.swaplevel(0, 1).sort_index()
  36.  
  37. In [116]: dft2.loc[idx[:, '2013-01-05'], :]
  38. Out[116]:
  39. A
  40. a 2013-01-05 00:00:00 0.122297
  41. 2013-01-05 12:00:00 0.370079
  42. b 2013-01-05 00:00:00 1.422060
  43. 2013-01-05 12:00:00 1.016331

New in version 0.25.0.

Slicing with string indexing also honors UTC offset.

  1. In [117]: df = pd.DataFrame([0], index=pd.DatetimeIndex(['2019-01-01'], tz='US/Pacific'))
  2.  
  3. In [118]: df
  4. Out[118]:
  5. 0
  6. 2019-01-01 00:00:00-08:00 0
  7.  
  8. In [119]: df['2019-01-01 12:00:00+04:00':'2019-01-01 13:00:00+04:00']
  9. Out[119]:
  10. 0
  11. 2019-01-01 00:00:00-08:00 0

Slice vs. exact match

Changed in version 0.20.0.

The same string used as an indexing parameter can be treated either as a slice or as an exact match depending on the resolution of the index. If the string is less accurate than the index, it will be treated as a slice, otherwise as an exact match.

Consider a Series object with a minute resolution index:

  1. In [120]: series_minute = pd.Series([1, 2, 3],
  2. .....: pd.DatetimeIndex(['2011-12-31 23:59:00',
  3. .....: '2012-01-01 00:00:00',
  4. .....: '2012-01-01 00:02:00']))
  5. .....:
  6.  
  7. In [121]: series_minute.index.resolution
  8. Out[121]: 'minute'

A timestamp string less accurate than a minute gives a Series object.

  1. In [122]: series_minute['2011-12-31 23']
  2. Out[122]:
  3. 2011-12-31 23:59:00 1
  4. dtype: int64

A timestamp string with minute resolution (or more accurate), gives a scalar instead, i.e. it is not casted to a slice.

  1. In [123]: series_minute['2011-12-31 23:59']
  2. Out[123]: 1
  3.  
  4. In [124]: series_minute['2011-12-31 23:59:00']
  5. Out[124]: 1

If index resolution is second, then the minute-accurate timestamp gives aSeries.

  1. In [125]: series_second = pd.Series([1, 2, 3],
  2. .....: pd.DatetimeIndex(['2011-12-31 23:59:59',
  3. .....: '2012-01-01 00:00:00',
  4. .....: '2012-01-01 00:00:01']))
  5. .....:
  6.  
  7. In [126]: series_second.index.resolution
  8. Out[126]: 'second'
  9.  
  10. In [127]: series_second['2011-12-31 23:59']
  11. Out[127]:
  12. 2011-12-31 23:59:59 1
  13. dtype: int64

If the timestamp string is treated as a slice, it can be used to index DataFrame with [] as well.

  1. In [128]: dft_minute = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]},
  2. .....: index=series_minute.index)
  3. .....:
  4.  
  5. In [129]: dft_minute['2011-12-31 23']
  6. Out[129]:
  7. a b
  8. 2011-12-31 23:59:00 1 4

Warning

However, if the string is treated as an exact match, the selection in DataFrame’s [] will be column-wise and not row-wise, see Indexing Basics. For example dft_minute['2011-12-31 23:59'] will raise KeyError as '2012-12-31 23:59' has the same resolution as the index and there is no column with such name:

To always have unambiguous selection, whether the row is treated as a slice or a single selection, use .loc.

  1. In [130]: dft_minute.loc['2011-12-31 23:59']
  2. Out[130]:
  3. a 1
  4. b 4
  5. Name: 2011-12-31 23:59:00, dtype: int64

Note also that DatetimeIndex resolution cannot be less precise than day.

  1. In [131]: series_monthly = pd.Series([1, 2, 3],
  2. .....: pd.DatetimeIndex(['2011-12', '2012-01', '2012-02']))
  3. .....:
  4.  
  5. In [132]: series_monthly.index.resolution
  6. Out[132]: 'day'
  7.  
  8. In [133]: series_monthly['2011-12'] # returns Series
  9. Out[133]:
  10. 2011-12-01 1
  11. dtype: int64

Exact indexing

As discussed in previous section, indexing a DatetimeIndex with a partial string depends on the “accuracy” of the period, in other words how specific the interval is in relation to the resolution of the index. In contrast, indexing with Timestamp or datetime objects is exact, because the objects have exact meaning. These also follow the semantics of including both endpoints.

These Timestamp and datetime objects have exact hours, minutes, and seconds, even though they were not explicitly specified (they are 0).

  1. In [134]: dft[datetime.datetime(2013, 1, 1):datetime.datetime(2013, 2, 28)]
  2. Out[134]:
  3. A
  4. 2013-01-01 00:00:00 0.276232
  5. 2013-01-01 00:01:00 -1.087401
  6. 2013-01-01 00:02:00 -0.673690
  7. 2013-01-01 00:03:00 0.113648
  8. 2013-01-01 00:04:00 -1.478427
  9. ... ...
  10. 2013-02-27 23:56:00 1.197749
  11. 2013-02-27 23:57:00 0.720521
  12. 2013-02-27 23:58:00 -0.072718
  13. 2013-02-27 23:59:00 -0.681192
  14. 2013-02-28 00:00:00 -0.557501
  15.  
  16. [83521 rows x 1 columns]

With no defaults.

  1. In [135]: dft[datetime.datetime(2013, 1, 1, 10, 12, 0):
  2. .....: datetime.datetime(2013, 2, 28, 10, 12, 0)]
  3. .....:
  4. Out[135]:
  5. A
  6. 2013-01-01 10:12:00 0.565375
  7. 2013-01-01 10:13:00 0.068184
  8. 2013-01-01 10:14:00 0.788871
  9. 2013-01-01 10:15:00 -0.280343
  10. 2013-01-01 10:16:00 0.931536
  11. ... ...
  12. 2013-02-28 10:08:00 0.148098
  13. 2013-02-28 10:09:00 -0.388138
  14. 2013-02-28 10:10:00 0.139348
  15. 2013-02-28 10:11:00 0.085288
  16. 2013-02-28 10:12:00 0.950146
  17.  
  18. [83521 rows x 1 columns]

Truncating & fancy indexing

A truncate() convenience function is provided that is similarto slicing. Note that truncate assumes a 0 value for any unspecified datecomponent in a DatetimeIndex in contrast to slicing which returns anypartially matching dates:

  1. In [136]: rng2 = pd.date_range('2011-01-01', '2012-01-01', freq='W')
  2.  
  3. In [137]: ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)
  4.  
  5. In [138]: ts2.truncate(before='2011-11', after='2011-12')
  6. Out[138]:
  7. 2011-11-06 0.437823
  8. 2011-11-13 -0.293083
  9. 2011-11-20 -0.059881
  10. 2011-11-27 1.252450
  11. Freq: W-SUN, dtype: float64
  12.  
  13. In [139]: ts2['2011-11':'2011-12']
  14. Out[139]:
  15. 2011-11-06 0.437823
  16. 2011-11-13 -0.293083
  17. 2011-11-20 -0.059881
  18. 2011-11-27 1.252450
  19. 2011-12-04 0.046611
  20. 2011-12-11 0.059478
  21. 2011-12-18 -0.286539
  22. 2011-12-25 0.841669
  23. Freq: W-SUN, dtype: float64

Even complicated fancy indexing that breaks the DatetimeIndex frequencyregularity will result in a DatetimeIndex, although frequency is lost:

  1. In [140]: ts2[[0, 2, 6]].index
  2. Out[140]: DatetimeIndex(['2011-01-02', '2011-01-16', '2011-02-13'], dtype='datetime64[ns]', freq=None)

Time/date components

There are several time/date properties that one can access from Timestamp or a collection of timestamps like a DatetimeIndex.

PropertyDescription
yearThe year of the datetime
monthThe month of the datetime
dayThe days of the datetime
hourThe hour of the datetime
minuteThe minutes of the datetime
secondThe seconds of the datetime
microsecondThe microseconds of the datetime
nanosecondThe nanoseconds of the datetime
dateReturns datetime.date (does not contain timezone information)
timeReturns datetime.time (does not contain timezone information)
timetzReturns datetime.time as local time with timezone information
dayofyearThe ordinal day of year
weekofyearThe week ordinal of the year
weekThe week ordinal of the year
dayofweekThe number of the day of the week with Monday=0, Sunday=6
weekdayThe number of the day of the week with Monday=0, Sunday=6
weekday_nameThe name of the day in a week (ex: Friday)
quarterQuarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc.
days_in_monthThe number of days in the month of the datetime
is_month_startLogical indicating if first day of month (defined by frequency)
is_month_endLogical indicating if last day of month (defined by frequency)
is_quarter_startLogical indicating if first day of quarter (defined by frequency)
is_quarter_endLogical indicating if last day of quarter (defined by frequency)
is_year_startLogical indicating if first day of year (defined by frequency)
is_year_endLogical indicating if last day of year (defined by frequency)
is_leap_yearLogical indicating if the date belongs to a leap year

Furthermore, if you have a Series with datetimelike values, then you canaccess these properties via the .dt accessor, as detailed in the sectionon .dt accessors.

DateOffset objects

In the preceding examples, frequency strings (e.g. 'D') were used to specifya frequency that defined:

These frequency strings map to a DateOffset object and its subclasses. A DateOffsetis similar to a Timedelta that represents a duration of time but follows specific calendar duration rules.For example, a Timedelta day will always increment datetimes by 24 hours, while a DateOffset daywill increment datetimes to the same time the next day whether a day represents 23, 24 or 25 hours due to daylightsavings time. However, all DateOffset subclasses that are an hour or smaller(Hour, Minute, Second, Milli, Micro, Nano) behave likeTimedelta and respect absolute time.

The basic DateOffset acts similar to dateutil.relativedelta (relativedelta documentation)that shifts a date time by the corresponding calendar duration specified. Thearithmetic operator (+) or the apply method can be used to perform the shift.

  1. # This particular day contains a day light savings time transition
  2. In [141]: ts = pd.Timestamp('2016-10-30 00:00:00', tz='Europe/Helsinki')
  3.  
  4. # Respects absolute time
  5. In [142]: ts + pd.Timedelta(days=1)
  6. Out[142]: Timestamp('2016-10-30 23:00:00+0200', tz='Europe/Helsinki')
  7.  
  8. # Respects calendar time
  9. In [143]: ts + pd.DateOffset(days=1)
  10. Out[143]: Timestamp('2016-10-31 00:00:00+0200', tz='Europe/Helsinki')
  11.  
  12. In [144]: friday = pd.Timestamp('2018-01-05')
  13.  
  14. In [145]: friday.day_name()
  15. Out[145]: 'Friday'
  16.  
  17. # Add 2 business days (Friday --> Tuesday)
  18. In [146]: two_business_days = 2 * pd.offsets.BDay()
  19.  
  20. In [147]: two_business_days.apply(friday)
  21. Out[147]: Timestamp('2018-01-09 00:00:00')
  22.  
  23. In [148]: friday + two_business_days
  24. Out[148]: Timestamp('2018-01-09 00:00:00')
  25.  
  26. In [149]: (friday + two_business_days).day_name()
  27. Out[149]: 'Tuesday'

Most DateOffsets have associated frequencies strings, or offset aliases, that can be passedinto freq keyword arguments. The available date offsets and associated frequency strings can be found below:

Date OffsetFrequency StringDescription
DateOffsetNoneGeneric offset class, defaults to 1 calendar day
BDay or BusinessDay'B'business day (weekday)
CDay or CustomBusinessDay'C'custom business day
Week'W'one week, optionally anchored on a day of the week
WeekOfMonth'WOM'the x-th day of the y-th week of each month
LastWeekOfMonth'LWOM'the x-th day of the last week of each month
MonthEnd'M'calendar month end
MonthBegin'MS'calendar month begin
BMonthEnd or BusinessMonthEnd'BM'business month end
BMonthBegin or BusinessMonthBegin'BMS'business month begin
CBMonthEnd or CustomBusinessMonthEnd'CBM'custom business month end
CBMonthBegin or CustomBusinessMonthBegin'CBMS'custom business month begin
SemiMonthEnd'SM'15th (or other day_of_month) and calendar month end
SemiMonthBegin'SMS'15th (or other day_of_month) and calendar month begin
QuarterEnd'Q'calendar quarter end
QuarterBegin'QS'calendar quarter begin
BQuarterEnd'BQbusiness quarter end
BQuarterBegin'BQS'business quarter begin
FY5253Quarter'REQ'retail (aka 52-53 week) quarter
YearEnd'A'calendar year end
YearBegin'AS' or 'BYS'calendar year begin
BYearEnd'BA'business year end
BYearBegin'BAS'business year begin
FY5253'RE'retail (aka 52-53 week) year
EasterNoneEaster holiday
BusinessHour'BH'business hour
CustomBusinessHour'CBH'custom business hour
Day'D'one absolute day
Hour'H'one hour
Minute'T' or 'min'one minute
Second'S'one second
Milli'L' or 'ms'one millisecond
Micro'U' or 'us'one microsecond
Nano'N'one nanosecond

DateOffsets additionally have rollforward() and rollback()methods for moving a date forward or backward respectively to a valid offsetdate relative to the offset. For example, business offsets will roll datesthat land on the weekends (Saturday and Sunday) forward to Monday sincebusiness offsets operate on the weekdays.

  1. In [150]: ts = pd.Timestamp('2018-01-06 00:00:00')
  2.  
  3. In [151]: ts.day_name()
  4. Out[151]: 'Saturday'
  5.  
  6. # BusinessHour's valid offset dates are Monday through Friday
  7. In [152]: offset = pd.offsets.BusinessHour(start='09:00')
  8.  
  9. # Bring the date to the closest offset date (Monday)
  10. In [153]: offset.rollforward(ts)
  11. Out[153]: Timestamp('2018-01-08 09:00:00')
  12.  
  13. # Date is brought to the closest offset date first and then the hour is added
  14. In [154]: ts + offset
  15. Out[154]: Timestamp('2018-01-08 10:00:00')

These operations preserve time (hour, minute, etc) information by default.To reset time to midnight, use normalize() before or after applyingthe operation (depending on whether you want the time information includedin the operation).

  1. In [155]: ts = pd.Timestamp('2014-01-01 09:00')
  2.  
  3. In [156]: day = pd.offsets.Day()
  4.  
  5. In [157]: day.apply(ts)
  6. Out[157]: Timestamp('2014-01-02 09:00:00')
  7.  
  8. In [158]: day.apply(ts).normalize()
  9. Out[158]: Timestamp('2014-01-02 00:00:00')
  10.  
  11. In [159]: ts = pd.Timestamp('2014-01-01 22:00')
  12.  
  13. In [160]: hour = pd.offsets.Hour()
  14.  
  15. In [161]: hour.apply(ts)
  16. Out[161]: Timestamp('2014-01-01 23:00:00')
  17.  
  18. In [162]: hour.apply(ts).normalize()
  19. Out[162]: Timestamp('2014-01-01 00:00:00')
  20.  
  21. In [163]: hour.apply(pd.Timestamp("2014-01-01 23:30")).normalize()
  22. Out[163]: Timestamp('2014-01-02 00:00:00')

Parametric offsets

Some of the offsets can be “parameterized” when created to result in differentbehaviors. For example, the Week offset for generating weekly data accepts aweekday parameter which results in the generated dates always lying on aparticular day of the week:

  1. In [164]: d = datetime.datetime(2008, 8, 18, 9, 0)
  2.  
  3. In [165]: d
  4. Out[165]: datetime.datetime(2008, 8, 18, 9, 0)
  5.  
  6. In [166]: d + pd.offsets.Week()
  7. Out[166]: Timestamp('2008-08-25 09:00:00')
  8.  
  9. In [167]: d + pd.offsets.Week(weekday=4)
  10. Out[167]: Timestamp('2008-08-22 09:00:00')
  11.  
  12. In [168]: (d + pd.offsets.Week(weekday=4)).weekday()
  13. Out[168]: 4
  14.  
  15. In [169]: d - pd.offsets.Week()
  16. Out[169]: Timestamp('2008-08-11 09:00:00')

The normalize option will be effective for addition and subtraction.

  1. In [170]: d + pd.offsets.Week(normalize=True)
  2. Out[170]: Timestamp('2008-08-25 00:00:00')
  3.  
  4. In [171]: d - pd.offsets.Week(normalize=True)
  5. Out[171]: Timestamp('2008-08-11 00:00:00')

Another example is parameterizing YearEnd with the specific ending month:

  1. In [172]: d + pd.offsets.YearEnd()
  2. Out[172]: Timestamp('2008-12-31 09:00:00')
  3.  
  4. In [173]: d + pd.offsets.YearEnd(month=6)
  5. Out[173]: Timestamp('2009-06-30 09:00:00')

Using offsets with Series / DatetimeIndex

Offsets can be used with either a Series or DatetimeIndex toapply the offset to each element.

  1. In [174]: rng = pd.date_range('2012-01-01', '2012-01-03')
  2.  
  3. In [175]: s = pd.Series(rng)
  4.  
  5. In [176]: rng
  6. Out[176]: DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03'], dtype='datetime64[ns]', freq='D')
  7.  
  8. In [177]: rng + pd.DateOffset(months=2)
  9. Out[177]: DatetimeIndex(['2012-03-01', '2012-03-02', '2012-03-03'], dtype='datetime64[ns]', freq='D')
  10.  
  11. In [178]: s + pd.DateOffset(months=2)
  12. Out[178]:
  13. 0 2012-03-01
  14. 1 2012-03-02
  15. 2 2012-03-03
  16. dtype: datetime64[ns]
  17.  
  18. In [179]: s - pd.DateOffset(months=2)
  19. Out[179]:
  20. 0 2011-11-01
  21. 1 2011-11-02
  22. 2 2011-11-03
  23. dtype: datetime64[ns]

If the offset class maps directly to a Timedelta (Day, Hour,Minute, Second, Micro, Milli, Nano) it can beused exactly like a Timedelta - see theTimedelta section for more examples.

  1. In [180]: s - pd.offsets.Day(2)
  2. Out[180]:
  3. 0 2011-12-30
  4. 1 2011-12-31
  5. 2 2012-01-01
  6. dtype: datetime64[ns]
  7.  
  8. In [181]: td = s - pd.Series(pd.date_range('2011-12-29', '2011-12-31'))
  9.  
  10. In [182]: td
  11. Out[182]:
  12. 0 3 days
  13. 1 3 days
  14. 2 3 days
  15. dtype: timedelta64[ns]
  16.  
  17. In [183]: td + pd.offsets.Minute(15)
  18. Out[183]:
  19. 0 3 days 00:15:00
  20. 1 3 days 00:15:00
  21. 2 3 days 00:15:00
  22. dtype: timedelta64[ns]

Note that some offsets (such as BQuarterEnd) do not have avectorized implementation. They can still be used but maycalculate significantly slower and will show a PerformanceWarning

  1. In [184]: rng + pd.offsets.BQuarterEnd()
  2. Out[184]: DatetimeIndex(['2012-03-30', '2012-03-30', '2012-03-30'], dtype='datetime64[ns]', freq='D')

Custom business days

The CDay or CustomBusinessDay class provides a parametricBusinessDay class which can be used to create customized business daycalendars which account for local holidays and local weekend conventions.

As an interesting example, let’s look at Egypt where a Friday-Saturday weekend is observed.

  1. In [185]: weekmask_egypt = 'Sun Mon Tue Wed Thu'
  2.  
  3. # They also observe International Workers' Day so let's
  4. # add that for a couple of years
  5. In [186]: holidays = ['2012-05-01',
  6. .....: datetime.datetime(2013, 5, 1),
  7. .....: np.datetime64('2014-05-01')]
  8. .....:
  9.  
  10. In [187]: bday_egypt = pd.offsets.CustomBusinessDay(holidays=holidays,
  11. .....: weekmask=weekmask_egypt)
  12. .....:
  13.  
  14. In [188]: dt = datetime.datetime(2013, 4, 30)
  15.  
  16. In [189]: dt + 2 * bday_egypt
  17. Out[189]: Timestamp('2013-05-05 00:00:00')

Let’s map to the weekday names:

  1. In [190]: dts = pd.date_range(dt, periods=5, freq=bday_egypt)
  2.  
  3. In [191]: pd.Series(dts.weekday, dts).map(
  4. .....: pd.Series('Mon Tue Wed Thu Fri Sat Sun'.split()))
  5. .....:
  6. Out[191]:
  7. 2013-04-30 Tue
  8. 2013-05-02 Thu
  9. 2013-05-05 Sun
  10. 2013-05-06 Mon
  11. 2013-05-07 Tue
  12. Freq: C, dtype: object

Holiday calendars can be used to provide the list of holidays. See theholiday calendar section for more information.

  1. In [192]: from pandas.tseries.holiday import USFederalHolidayCalendar
  2.  
  3. In [193]: bday_us = pd.offsets.CustomBusinessDay(calendar=USFederalHolidayCalendar())
  4.  
  5. # Friday before MLK Day
  6. In [194]: dt = datetime.datetime(2014, 1, 17)
  7.  
  8. # Tuesday after MLK Day (Monday is skipped because it's a holiday)
  9. In [195]: dt + bday_us
  10. Out[195]: Timestamp('2014-01-21 00:00:00')

Monthly offsets that respect a certain holiday calendar can be definedin the usual way.

  1. In [196]: bmth_us = pd.offsets.CustomBusinessMonthBegin(
  2. .....: calendar=USFederalHolidayCalendar())
  3. .....:
  4.  
  5. # Skip new years
  6. In [197]: dt = datetime.datetime(2013, 12, 17)
  7.  
  8. In [198]: dt + bmth_us
  9. Out[198]: Timestamp('2014-01-02 00:00:00')
  10.  
  11. # Define date index with custom offset
  12. In [199]: pd.date_range(start='20100101', end='20120101', freq=bmth_us)
  13. Out[199]:
  14. DatetimeIndex(['2010-01-04', '2010-02-01', '2010-03-01', '2010-04-01',
  15. '2010-05-03', '2010-06-01', '2010-07-01', '2010-08-02',
  16. '2010-09-01', '2010-10-01', '2010-11-01', '2010-12-01',
  17. '2011-01-03', '2011-02-01', '2011-03-01', '2011-04-01',
  18. '2011-05-02', '2011-06-01', '2011-07-01', '2011-08-01',
  19. '2011-09-01', '2011-10-03', '2011-11-01', '2011-12-01'],
  20. dtype='datetime64[ns]', freq='CBMS')

Note

The frequency string ‘C’ is used to indicate that a CustomBusinessDayDateOffset is used, it is important to note that since CustomBusinessDay isa parameterised type, instances of CustomBusinessDay may differ and this isnot detectable from the ‘C’ frequency string. The user therefore needs toensure that the ‘C’ frequency string is used consistently within the user’sapplication.

Business hour

The BusinessHour class provides a business hour representation on BusinessDay,allowing to use specific start and end times.

By default, BusinessHour uses 9:00 - 17:00 as business hours.Adding BusinessHour will increment Timestamp by hourly frequency.If target Timestamp is out of business hours, move to the next business hourthen increment it. If the result exceeds the business hours end, the remaininghours are added to the next business day.

  1. In [200]: bh = pd.offsets.BusinessHour()
  2.  
  3. In [201]: bh
  4. Out[201]: <BusinessHour: BH=09:00-17:00>
  5.  
  6. # 2014-08-01 is Friday
  7. In [202]: pd.Timestamp('2014-08-01 10:00').weekday()
  8. Out[202]: 4
  9.  
  10. In [203]: pd.Timestamp('2014-08-01 10:00') + bh
  11. Out[203]: Timestamp('2014-08-01 11:00:00')
  12.  
  13. # Below example is the same as: pd.Timestamp('2014-08-01 09:00') + bh
  14. In [204]: pd.Timestamp('2014-08-01 08:00') + bh
  15. Out[204]: Timestamp('2014-08-01 10:00:00')
  16.  
  17. # If the results is on the end time, move to the next business day
  18. In [205]: pd.Timestamp('2014-08-01 16:00') + bh
  19. Out[205]: Timestamp('2014-08-04 09:00:00')
  20.  
  21. # Remainings are added to the next day
  22. In [206]: pd.Timestamp('2014-08-01 16:30') + bh
  23. Out[206]: Timestamp('2014-08-04 09:30:00')
  24.  
  25. # Adding 2 business hours
  26. In [207]: pd.Timestamp('2014-08-01 10:00') + pd.offsets.BusinessHour(2)
  27. Out[207]: Timestamp('2014-08-01 12:00:00')
  28.  
  29. # Subtracting 3 business hours
  30. In [208]: pd.Timestamp('2014-08-01 10:00') + pd.offsets.BusinessHour(-3)
  31. Out[208]: Timestamp('2014-07-31 15:00:00')

You can also specify start and end time by keywords. The argument mustbe a str with an hour:minute representation or a datetime.timeinstance. Specifying seconds, microseconds and nanoseconds as business hourresults in ValueError.

  1. In [209]: bh = pd.offsets.BusinessHour(start='11:00', end=datetime.time(20, 0))
  2.  
  3. In [210]: bh
  4. Out[210]: <BusinessHour: BH=11:00-20:00>
  5.  
  6. In [211]: pd.Timestamp('2014-08-01 13:00') + bh
  7. Out[211]: Timestamp('2014-08-01 14:00:00')
  8.  
  9. In [212]: pd.Timestamp('2014-08-01 09:00') + bh
  10. Out[212]: Timestamp('2014-08-01 12:00:00')
  11.  
  12. In [213]: pd.Timestamp('2014-08-01 18:00') + bh
  13. Out[213]: Timestamp('2014-08-01 19:00:00')

Passing start time later than end represents midnight business hour.In this case, business hour exceeds midnight and overlap to the next day.Valid business hours are distinguished by whether it started from valid BusinessDay.

  1. In [214]: bh = pd.offsets.BusinessHour(start='17:00', end='09:00')
  2.  
  3. In [215]: bh
  4. Out[215]: <BusinessHour: BH=17:00-09:00>
  5.  
  6. In [216]: pd.Timestamp('2014-08-01 17:00') + bh
  7. Out[216]: Timestamp('2014-08-01 18:00:00')
  8.  
  9. In [217]: pd.Timestamp('2014-08-01 23:00') + bh
  10. Out[217]: Timestamp('2014-08-02 00:00:00')
  11.  
  12. # Although 2014-08-02 is Saturday,
  13. # it is valid because it starts from 08-01 (Friday).
  14. In [218]: pd.Timestamp('2014-08-02 04:00') + bh
  15. Out[218]: Timestamp('2014-08-02 05:00:00')
  16.  
  17. # Although 2014-08-04 is Monday,
  18. # it is out of business hours because it starts from 08-03 (Sunday).
  19. In [219]: pd.Timestamp('2014-08-04 04:00') + bh
  20. Out[219]: Timestamp('2014-08-04 18:00:00')

Applying BusinessHour.rollforward and rollback to out of business hours results inthe next business hour start or previous day’s end. Different from other offsets, BusinessHour.rollforwardmay output different results from apply by definition.

This is because one day’s business hour end is equal to next day’s business hour start. For example,under the default business hours (9:00 - 17:00), there is no gap (0 minutes) between 2014-08-01 17:00 and2014-08-04 09:00.

  1. # This adjusts a Timestamp to business hour edge
  2. In [220]: pd.offsets.BusinessHour().rollback(pd.Timestamp('2014-08-02 15:00'))
  3. Out[220]: Timestamp('2014-08-01 17:00:00')
  4.  
  5. In [221]: pd.offsets.BusinessHour().rollforward(pd.Timestamp('2014-08-02 15:00'))
  6. Out[221]: Timestamp('2014-08-04 09:00:00')
  7.  
  8. # It is the same as BusinessHour().apply(pd.Timestamp('2014-08-01 17:00')).
  9. # And it is the same as BusinessHour().apply(pd.Timestamp('2014-08-04 09:00'))
  10. In [222]: pd.offsets.BusinessHour().apply(pd.Timestamp('2014-08-02 15:00'))
  11. Out[222]: Timestamp('2014-08-04 10:00:00')
  12.  
  13. # BusinessDay results (for reference)
  14. In [223]: pd.offsets.BusinessHour().rollforward(pd.Timestamp('2014-08-02'))
  15. Out[223]: Timestamp('2014-08-04 09:00:00')
  16.  
  17. # It is the same as BusinessDay().apply(pd.Timestamp('2014-08-01'))
  18. # The result is the same as rollworward because BusinessDay never overlap.
  19. In [224]: pd.offsets.BusinessHour().apply(pd.Timestamp('2014-08-02'))
  20. Out[224]: Timestamp('2014-08-04 10:00:00')

BusinessHour regards Saturday and Sunday as holidays. To use arbitraryholidays, you can use CustomBusinessHour offset, as explained in thefollowing subsection.

Custom business hour

New in version 0.18.1.

The CustomBusinessHour is a mixture of BusinessHour and CustomBusinessDay whichallows you to specify arbitrary holidays. CustomBusinessHour works as the sameas BusinessHour except that it skips specified custom holidays.

  1. In [225]: from pandas.tseries.holiday import USFederalHolidayCalendar
  2.  
  3. In [226]: bhour_us = pd.offsets.CustomBusinessHour(calendar=USFederalHolidayCalendar())
  4.  
  5. # Friday before MLK Day
  6. In [227]: dt = datetime.datetime(2014, 1, 17, 15)
  7.  
  8. In [228]: dt + bhour_us
  9. Out[228]: Timestamp('2014-01-17 16:00:00')
  10.  
  11. # Tuesday after MLK Day (Monday is skipped because it's a holiday)
  12. In [229]: dt + bhour_us * 2
  13. Out[229]: Timestamp('2014-01-21 09:00:00')

You can use keyword arguments supported by either BusinessHour and CustomBusinessDay.

  1. In [230]: bhour_mon = pd.offsets.CustomBusinessHour(start='10:00',
  2. .....: weekmask='Tue Wed Thu Fri')
  3. .....:
  4.  
  5. # Monday is skipped because it's a holiday, business hour starts from 10:00
  6. In [231]: dt + bhour_mon * 2
  7. Out[231]: Timestamp('2014-01-21 10:00:00')

Offset aliases

A number of string aliases are given to useful common time seriesfrequencies. We will refer to these aliases as offset aliases.

AliasDescription
Bbusiness day frequency
Ccustom business day frequency
Dcalendar day frequency
Wweekly frequency
Mmonth end frequency
SMsemi-month end frequency (15th and end of month)
BMbusiness month end frequency
CBMcustom business month end frequency
MSmonth start frequency
SMSsemi-month start frequency (1st and 15th)
BMSbusiness month start frequency
CBMScustom business month start frequency
Qquarter end frequency
BQbusiness quarter end frequency
QSquarter start frequency
BQSbusiness quarter start frequency
A, Yyear end frequency
BA, BYbusiness year end frequency
AS, YSyear start frequency
BAS, BYSbusiness year start frequency
BHbusiness hour frequency
Hhourly frequency
T, minminutely frequency
Ssecondly frequency
L, msmilliseconds
U, usmicroseconds
Nnanoseconds

Combining aliases

As we have seen previously, the alias and the offset instance are fungible inmost functions:

  1. In [232]: pd.date_range(start, periods=5, freq='B')
  2. Out[232]:
  3. DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
  4. '2011-01-07'],
  5. dtype='datetime64[ns]', freq='B')
  6.  
  7. In [233]: pd.date_range(start, periods=5, freq=pd.offsets.BDay())
  8. Out[233]:
  9. DatetimeIndex(['2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06',
  10. '2011-01-07'],
  11. dtype='datetime64[ns]', freq='B')

You can combine together day and intraday offsets:

  1. In [234]: pd.date_range(start, periods=10, freq='2h20min')
  2. Out[234]:
  3. DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 02:20:00',
  4. '2011-01-01 04:40:00', '2011-01-01 07:00:00',
  5. '2011-01-01 09:20:00', '2011-01-01 11:40:00',
  6. '2011-01-01 14:00:00', '2011-01-01 16:20:00',
  7. '2011-01-01 18:40:00', '2011-01-01 21:00:00'],
  8. dtype='datetime64[ns]', freq='140T')
  9.  
  10. In [235]: pd.date_range(start, periods=10, freq='1D10U')
  11. Out[235]:
  12. DatetimeIndex([ '2011-01-01 00:00:00', '2011-01-02 00:00:00.000010',
  13. '2011-01-03 00:00:00.000020', '2011-01-04 00:00:00.000030',
  14. '2011-01-05 00:00:00.000040', '2011-01-06 00:00:00.000050',
  15. '2011-01-07 00:00:00.000060', '2011-01-08 00:00:00.000070',
  16. '2011-01-09 00:00:00.000080', '2011-01-10 00:00:00.000090'],
  17. dtype='datetime64[ns]', freq='86400000010U')

Anchored offsets

For some frequencies you can specify an anchoring suffix:

AliasDescription
W-SUNweekly frequency (Sundays). Same as ‘W’
W-MONweekly frequency (Mondays)
W-TUEweekly frequency (Tuesdays)
W-WEDweekly frequency (Wednesdays)
W-THUweekly frequency (Thursdays)
W-FRIweekly frequency (Fridays)
W-SATweekly frequency (Saturdays)
(B)Q(S)-DECquarterly frequency, year ends in December. Same as ‘Q’
(B)Q(S)-JANquarterly frequency, year ends in January
(B)Q(S)-FEBquarterly frequency, year ends in February
(B)Q(S)-MARquarterly frequency, year ends in March
(B)Q(S)-APRquarterly frequency, year ends in April
(B)Q(S)-MAYquarterly frequency, year ends in May
(B)Q(S)-JUNquarterly frequency, year ends in June
(B)Q(S)-JULquarterly frequency, year ends in July
(B)Q(S)-AUGquarterly frequency, year ends in August
(B)Q(S)-SEPquarterly frequency, year ends in September
(B)Q(S)-OCTquarterly frequency, year ends in October
(B)Q(S)-NOVquarterly frequency, year ends in November
(B)A(S)-DECannual frequency, anchored end of December. Same as ‘A’
(B)A(S)-JANannual frequency, anchored end of January
(B)A(S)-FEBannual frequency, anchored end of February
(B)A(S)-MARannual frequency, anchored end of March
(B)A(S)-APRannual frequency, anchored end of April
(B)A(S)-MAYannual frequency, anchored end of May
(B)A(S)-JUNannual frequency, anchored end of June
(B)A(S)-JULannual frequency, anchored end of July
(B)A(S)-AUGannual frequency, anchored end of August
(B)A(S)-SEPannual frequency, anchored end of September
(B)A(S)-OCTannual frequency, anchored end of October
(B)A(S)-NOVannual frequency, anchored end of November

These can be used as arguments to date_range, bdate_range, constructorsfor DatetimeIndex, as well as various other timeseries-related functionsin pandas.

Anchored offset semantics

For those offsets that are anchored to the start or end of specificfrequency (MonthEnd, MonthBegin, WeekEnd, etc), the followingrules apply to rolling forward and backwards.

When n is not 0, if the given date is not on an anchor point, it snapped to the next(previous)anchor point, and moved |n|-1 additional steps forwards or backwards.

  1. In [236]: pd.Timestamp('2014-01-02') + pd.offsets.MonthBegin(n=1)
  2. Out[236]: Timestamp('2014-02-01 00:00:00')
  3.  
  4. In [237]: pd.Timestamp('2014-01-02') + pd.offsets.MonthEnd(n=1)
  5. Out[237]: Timestamp('2014-01-31 00:00:00')
  6.  
  7. In [238]: pd.Timestamp('2014-01-02') - pd.offsets.MonthBegin(n=1)
  8. Out[238]: Timestamp('2014-01-01 00:00:00')
  9.  
  10. In [239]: pd.Timestamp('2014-01-02') - pd.offsets.MonthEnd(n=1)
  11. Out[239]: Timestamp('2013-12-31 00:00:00')
  12.  
  13. In [240]: pd.Timestamp('2014-01-02') + pd.offsets.MonthBegin(n=4)
  14. Out[240]: Timestamp('2014-05-01 00:00:00')
  15.  
  16. In [241]: pd.Timestamp('2014-01-02') - pd.offsets.MonthBegin(n=4)
  17. Out[241]: Timestamp('2013-10-01 00:00:00')

If the given date is on an anchor point, it is moved |n| points forwardsor backwards.

  1. In [242]: pd.Timestamp('2014-01-01') + pd.offsets.MonthBegin(n=1)
  2. Out[242]: Timestamp('2014-02-01 00:00:00')
  3.  
  4. In [243]: pd.Timestamp('2014-01-31') + pd.offsets.MonthEnd(n=1)
  5. Out[243]: Timestamp('2014-02-28 00:00:00')
  6.  
  7. In [244]: pd.Timestamp('2014-01-01') - pd.offsets.MonthBegin(n=1)
  8. Out[244]: Timestamp('2013-12-01 00:00:00')
  9.  
  10. In [245]: pd.Timestamp('2014-01-31') - pd.offsets.MonthEnd(n=1)
  11. Out[245]: Timestamp('2013-12-31 00:00:00')
  12.  
  13. In [246]: pd.Timestamp('2014-01-01') + pd.offsets.MonthBegin(n=4)
  14. Out[246]: Timestamp('2014-05-01 00:00:00')
  15.  
  16. In [247]: pd.Timestamp('2014-01-31') - pd.offsets.MonthBegin(n=4)
  17. Out[247]: Timestamp('2013-10-01 00:00:00')

For the case when n=0, the date is not moved if on an anchor point, otherwiseit is rolled forward to the next anchor point.

  1. In [248]: pd.Timestamp('2014-01-02') + pd.offsets.MonthBegin(n=0)
  2. Out[248]: Timestamp('2014-02-01 00:00:00')
  3.  
  4. In [249]: pd.Timestamp('2014-01-02') + pd.offsets.MonthEnd(n=0)
  5. Out[249]: Timestamp('2014-01-31 00:00:00')
  6.  
  7. In [250]: pd.Timestamp('2014-01-01') + pd.offsets.MonthBegin(n=0)
  8. Out[250]: Timestamp('2014-01-01 00:00:00')
  9.  
  10. In [251]: pd.Timestamp('2014-01-31') + pd.offsets.MonthEnd(n=0)
  11. Out[251]: Timestamp('2014-01-31 00:00:00')

Holidays / holiday calendars

Holidays and calendars provide a simple way to define holiday rules to be usedwith CustomBusinessDay or in other analysis that requires a predefinedset of holidays. The AbstractHolidayCalendar class provides all the necessarymethods to return a list of holidays and only rules need to be definedin a specific holiday calendar class. Furthermore, the start_date and end_dateclass attributes determine over what date range holidays are generated. Theseshould be overwritten on the AbstractHolidayCalendar class to have the rangeapply to all calendar subclasses. USFederalHolidayCalendar is theonly calendar that exists and primarily serves as an example for developingother calendars.

For holidays that occur on fixed dates (e.g., US Memorial Day or July 4th) anobservance rule determines when that holiday is observed if it falls on a weekendor some other non-observed day. Defined observance rules are:

RuleDescription
nearest_workdaymove Saturday to Friday and Sunday to Monday
sunday_to_mondaymove Sunday to following Monday
next_monday_or_tuesdaymove Saturday to Monday and Sunday/Monday to Tuesday
previous_fridaymove Saturday and Sunday to previous Friday”
next_mondaymove Saturday and Sunday to following Monday

An example of how holidays and holiday calendars are defined:

  1. In [252]: from pandas.tseries.holiday import Holiday, USMemorialDay,\
  2. .....: AbstractHolidayCalendar, nearest_workday, MO
  3. .....:
  4.  
  5. In [253]: class ExampleCalendar(AbstractHolidayCalendar):
  6. .....: rules = [
  7. .....: USMemorialDay,
  8. .....: Holiday('July 4th', month=7, day=4, observance=nearest_workday),
  9. .....: Holiday('Columbus Day', month=10, day=1,
  10. .....: offset=pd.DateOffset(weekday=MO(2)))]
  11. .....:
  12.  
  13. In [254]: cal = ExampleCalendar()
  14.  
  15. In [255]: cal.holidays(datetime.datetime(2012, 1, 1), datetime.datetime(2012, 12, 31))
  16. Out[255]: DatetimeIndex(['2012-05-28', '2012-07-04', '2012-10-08'], dtype='datetime64[ns]', freq=None)
hint:weekday=MO(2) is same as 2 * Week(weekday=2)

Using this calendar, creating an index or doing offset arithmetic skips weekendsand holidays (i.e., Memorial Day/July 4th). For example, the below definesa custom business day offset using the ExampleCalendar. Like any other offset,it can be used to create a DatetimeIndex or added to datetimeor Timestamp objects.

  1. In [256]: pd.date_range(start='7/1/2012', end='7/10/2012',
  2. .....: freq=pd.offsets.CDay(calendar=cal)).to_pydatetime()
  3. .....:
  4. Out[256]:
  5. array([datetime.datetime(2012, 7, 2, 0, 0),
  6. datetime.datetime(2012, 7, 3, 0, 0),
  7. datetime.datetime(2012, 7, 5, 0, 0),
  8. datetime.datetime(2012, 7, 6, 0, 0),
  9. datetime.datetime(2012, 7, 9, 0, 0),
  10. datetime.datetime(2012, 7, 10, 0, 0)], dtype=object)
  11.  
  12. In [257]: offset = pd.offsets.CustomBusinessDay(calendar=cal)
  13.  
  14. In [258]: datetime.datetime(2012, 5, 25) + offset
  15. Out[258]: Timestamp('2012-05-29 00:00:00')
  16.  
  17. In [259]: datetime.datetime(2012, 7, 3) + offset
  18. Out[259]: Timestamp('2012-07-05 00:00:00')
  19.  
  20. In [260]: datetime.datetime(2012, 7, 3) + 2 * offset
  21. Out[260]: Timestamp('2012-07-06 00:00:00')
  22.  
  23. In [261]: datetime.datetime(2012, 7, 6) + offset
  24. Out[261]: Timestamp('2012-07-09 00:00:00')

Ranges are defined by the start_date and end_date class attributesof AbstractHolidayCalendar. The defaults are shown below.

  1. In [262]: AbstractHolidayCalendar.start_date
  2. Out[262]: Timestamp('1970-01-01 00:00:00')
  3.  
  4. In [263]: AbstractHolidayCalendar.end_date
  5. Out[263]: Timestamp('2030-12-31 00:00:00')

These dates can be overwritten by setting the attributes asdatetime/Timestamp/string.

  1. In [264]: AbstractHolidayCalendar.start_date = datetime.datetime(2012, 1, 1)
  2.  
  3. In [265]: AbstractHolidayCalendar.end_date = datetime.datetime(2012, 12, 31)
  4.  
  5. In [266]: cal.holidays()
  6. Out[266]: DatetimeIndex(['2012-05-28', '2012-07-04', '2012-10-08'], dtype='datetime64[ns]', freq=None)

Every calendar class is accessible by name using the get_calendar functionwhich returns a holiday class instance. Any imported calendar class willautomatically be available by this function. Also, HolidayCalendarFactoryprovides an easy interface to create calendars that are combinations of calendarsor calendars with additional rules.

  1. In [267]: from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory,\
  2. .....: USLaborDay
  3. .....:
  4.  
  5. In [268]: cal = get_calendar('ExampleCalendar')
  6.  
  7. In [269]: cal.rules
  8. Out[269]:
  9. [Holiday: Memorial Day (month=5, day=31, offset=<DateOffset: weekday=MO(-1)>),
  10. Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0x7f450611f8c0>),
  11. Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: weekday=MO(+2)>)]
  12.  
  13. In [270]: new_cal = HolidayCalendarFactory('NewExampleCalendar', cal, USLaborDay)
  14.  
  15. In [271]: new_cal.rules
  16. Out[271]:
  17. [Holiday: Labor Day (month=9, day=1, offset=<DateOffset: weekday=MO(+1)>),
  18. Holiday: Memorial Day (month=5, day=31, offset=<DateOffset: weekday=MO(-1)>),
  19. Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0x7f450611f8c0>),
  20. Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: weekday=MO(+2)>)]

Shifting / lagging

One may want to shift or lag the values in a time series back and forward intime. The method for this is shift(), which is available on all ofthe pandas objects.

  1. In [272]: ts = pd.Series(range(len(rng)), index=rng)
  2.  
  3. In [273]: ts = ts[:5]
  4.  
  5. In [274]: ts.shift(1)
  6. Out[274]:
  7. 2012-01-01 NaN
  8. 2012-01-02 0.0
  9. 2012-01-03 1.0
  10. Freq: D, dtype: float64

The shift method accepts an freq argument which can accept aDateOffset class or other timedelta-like object or also anoffset alias:

  1. In [275]: ts.shift(5, freq=pd.offsets.BDay())
  2. Out[275]:
  3. 2012-01-06 0
  4. 2012-01-09 1
  5. 2012-01-10 2
  6. Freq: B, dtype: int64
  7.  
  8. In [276]: ts.shift(5, freq='BM')
  9. Out[276]:
  10. 2012-05-31 0
  11. 2012-05-31 1
  12. 2012-05-31 2
  13. Freq: D, dtype: int64

Rather than changing the alignment of the data and the index, DataFrame andSeries objects also have a tshift() convenience method thatchanges all the dates in the index by a specified number of offsets:

  1. In [277]: ts.tshift(5, freq='D')
  2. Out[277]:
  3. 2012-01-06 0
  4. 2012-01-07 1
  5. 2012-01-08 2
  6. Freq: D, dtype: int64

Note that with tshift, the leading entry is no longer NaN because the datais not being realigned.

Frequency conversion

The primary function for changing frequencies is the asfreq()method. For a DatetimeIndex, this is basically just a thin, but convenientwrapper around reindex() which generates a date_range andcalls reindex.

  1. In [278]: dr = pd.date_range('1/1/2010', periods=3, freq=3 * pd.offsets.BDay())
  2.  
  3. In [279]: ts = pd.Series(np.random.randn(3), index=dr)
  4.  
  5. In [280]: ts
  6. Out[280]:
  7. 2010-01-01 1.494522
  8. 2010-01-06 -0.778425
  9. 2010-01-11 -0.253355
  10. Freq: 3B, dtype: float64
  11.  
  12. In [281]: ts.asfreq(pd.offsets.BDay())
  13. Out[281]:
  14. 2010-01-01 1.494522
  15. 2010-01-04 NaN
  16. 2010-01-05 NaN
  17. 2010-01-06 -0.778425
  18. 2010-01-07 NaN
  19. 2010-01-08 NaN
  20. 2010-01-11 -0.253355
  21. Freq: B, dtype: float64

asfreq provides a further convenience so you can specify an interpolationmethod for any gaps that may appear after the frequency conversion.

  1. In [282]: ts.asfreq(pd.offsets.BDay(), method='pad')
  2. Out[282]:
  3. 2010-01-01 1.494522
  4. 2010-01-04 1.494522
  5. 2010-01-05 1.494522
  6. 2010-01-06 -0.778425
  7. 2010-01-07 -0.778425
  8. 2010-01-08 -0.778425
  9. 2010-01-11 -0.253355
  10. Freq: B, dtype: float64

Filling forward / backward

Related to asfreq and reindex is fillna(), which isdocumented in the missing data section.

Converting to Python datetimes

DatetimeIndex can be converted to an array of Python nativedatetime.datetime objects using the to_pydatetime method.

Resampling

Warning

The interface to .resample has changed in 0.18.0 to be more groupby-like and hence more flexible.See the whatsnew docs for a comparison with prior versions.

Pandas has a simple, powerful, and efficient functionality for performingresampling operations during frequency conversion (e.g., converting secondlydata into 5-minutely data). This is extremely common in, but not limited to,financial applications.

resample() is a time-based groupby, followed by a reduction methodon each of its groups. See some cookbook examples forsome advanced strategies.

Starting in version 0.18.1, the resample() function can be used directly fromDataFrameGroupBy objects, see the groupby docs.

Note

.resample() is similar to using a rolling() operation witha time-based offset, see a discussion here.

Basics

  1. In [283]: rng = pd.date_range('1/1/2012', periods=100, freq='S')
  2.  
  3. In [284]: ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
  4.  
  5. In [285]: ts.resample('5Min').sum()
  6. Out[285]:
  7. 2012-01-01 25103
  8. Freq: 5T, dtype: int64

The resample function is very flexible and allows you to specify manydifferent parameters to control the frequency conversion and resamplingoperation.

Any function available via dispatching is available asa method of the returned object, including sum, mean, std, sem,max, min, median, first, last, ohlc:

  1. In [286]: ts.resample('5Min').mean()
  2. Out[286]:
  3. 2012-01-01 251.03
  4. Freq: 5T, dtype: float64
  5.  
  6. In [287]: ts.resample('5Min').ohlc()
  7. Out[287]:
  8. open high low close
  9. 2012-01-01 308 460 9 205
  10.  
  11. In [288]: ts.resample('5Min').max()
  12. Out[288]:
  13. 2012-01-01 460
  14. Freq: 5T, dtype: int64

For downsampling, closed can be set to ‘left’ or ‘right’ to specify whichend of the interval is closed:

  1. In [289]: ts.resample('5Min', closed='right').mean()
  2. Out[289]:
  3. 2011-12-31 23:55:00 308.000000
  4. 2012-01-01 00:00:00 250.454545
  5. Freq: 5T, dtype: float64
  6.  
  7. In [290]: ts.resample('5Min', closed='left').mean()
  8. Out[290]:
  9. 2012-01-01 251.03
  10. Freq: 5T, dtype: float64

Parameters like label and loffset are used to manipulate the resultinglabels. label specifies whether the result is labeled with the beginning orthe end of the interval. loffset performs a time adjustment on the outputlabels.

  1. In [291]: ts.resample('5Min').mean() # by default label='left'
  2. Out[291]:
  3. 2012-01-01 251.03
  4. Freq: 5T, dtype: float64
  5.  
  6. In [292]: ts.resample('5Min', label='left').mean()
  7. Out[292]:
  8. 2012-01-01 251.03
  9. Freq: 5T, dtype: float64
  10.  
  11. In [293]: ts.resample('5Min', label='left', loffset='1s').mean()
  12. Out[293]:
  13. 2012-01-01 00:00:01 251.03
  14. dtype: float64

Warning

The default values for label and closed is ‘left’ for allfrequency offsets except for ‘M’, ‘A’, ‘Q’, ‘BM’, ‘BA’, ‘BQ’, and ‘W’which all have a default of ‘right’.

This might unintendedly lead to looking ahead, where the value for a latertime is pulled back to a previous time as in the following example withthe BusinessDay frequency:

  1. In [294]: s = pd.date_range('2000-01-01', '2000-01-05').to_series()
  2.  
  3. In [295]: s.iloc[2] = pd.NaT
  4.  
  5. In [296]: s.dt.weekday_name
  6. Out[296]:
  7. 2000-01-01 Saturday
  8. 2000-01-02 Sunday
  9. 2000-01-03 NaN
  10. 2000-01-04 Tuesday
  11. 2000-01-05 Wednesday
  12. Freq: D, dtype: object
  13.  
  14. # default: label='left', closed='left'
  15. In [297]: s.resample('B').last().dt.weekday_name
  16. Out[297]:
  17. 1999-12-31 Sunday
  18. 2000-01-03 NaN
  19. 2000-01-04 Tuesday
  20. 2000-01-05 Wednesday
  21. Freq: B, dtype: object

Notice how the value for Sunday got pulled back to the previous Friday.To get the behavior where the value for Sunday is pushed to Monday, useinstead

  1. In [298]: s.resample('B', label='right', closed='right').last().dt.weekday_name
  2. Out[298]:
  3. 2000-01-03 Sunday
  4. 2000-01-04 Tuesday
  5. 2000-01-05 Wednesday
  6. Freq: B, dtype: object

The axis parameter can be set to 0 or 1 and allows you to resample thespecified axis for a DataFrame.

kind can be set to ‘timestamp’ or ‘period’ to convert the resulting indexto/from timestamp and time span representations. By default resampleretains the input representation.

convention can be set to ‘start’ or ‘end’ when resampling period data(detail below). It specifies how low frequency periods are converted to higherfrequency periods.

Upsampling

For upsampling, you can specify a way to upsample and the limit parameter to interpolate over the gaps that are created:

  1. # from secondly to every 250 milliseconds
  2. In [299]: ts[:2].resample('250L').asfreq()
  3. Out[299]:
  4. 2012-01-01 00:00:00.000 308.0
  5. 2012-01-01 00:00:00.250 NaN
  6. 2012-01-01 00:00:00.500 NaN
  7. 2012-01-01 00:00:00.750 NaN
  8. 2012-01-01 00:00:01.000 204.0
  9. Freq: 250L, dtype: float64
  10.  
  11. In [300]: ts[:2].resample('250L').ffill()
  12. Out[300]:
  13. 2012-01-01 00:00:00.000 308
  14. 2012-01-01 00:00:00.250 308
  15. 2012-01-01 00:00:00.500 308
  16. 2012-01-01 00:00:00.750 308
  17. 2012-01-01 00:00:01.000 204
  18. Freq: 250L, dtype: int64
  19.  
  20. In [301]: ts[:2].resample('250L').ffill(limit=2)
  21. Out[301]:
  22. 2012-01-01 00:00:00.000 308.0
  23. 2012-01-01 00:00:00.250 308.0
  24. 2012-01-01 00:00:00.500 308.0
  25. 2012-01-01 00:00:00.750 NaN
  26. 2012-01-01 00:00:01.000 204.0
  27. Freq: 250L, dtype: float64

Sparse resampling

Sparse timeseries are the ones where you have a lot fewer points relativeto the amount of time you are looking to resample. Naively upsampling a sparseseries can potentially generate lots of intermediate values. When you don’t wantto use a method to fill these values, e.g. fill_method is None, thenintermediate values will be filled with NaN.

Since resample is a time-based groupby, the following is a method to efficientlyresample only the groups that are not all NaN.

  1. In [302]: rng = pd.date_range('2014-1-1', periods=100, freq='D') + pd.Timedelta('1s')
  2.  
  3. In [303]: ts = pd.Series(range(100), index=rng)

If we want to resample to the full range of the series:

  1. In [304]: ts.resample('3T').sum()
  2. Out[304]:
  3. 2014-01-01 00:00:00 0
  4. 2014-01-01 00:03:00 0
  5. 2014-01-01 00:06:00 0
  6. 2014-01-01 00:09:00 0
  7. 2014-01-01 00:12:00 0
  8. ..
  9. 2014-04-09 23:48:00 0
  10. 2014-04-09 23:51:00 0
  11. 2014-04-09 23:54:00 0
  12. 2014-04-09 23:57:00 0
  13. 2014-04-10 00:00:00 99
  14. Freq: 3T, Length: 47521, dtype: int64

We can instead only resample those groups where we have points as follows:

  1. In [305]: from functools import partial
  2.  
  3. In [306]: from pandas.tseries.frequencies import to_offset
  4.  
  5. In [307]: def round(t, freq):
  6. .....: freq = to_offset(freq)
  7. .....: return pd.Timestamp((t.value // freq.delta.value) * freq.delta.value)
  8. .....:
  9.  
  10. In [308]: ts.groupby(partial(round, freq='3T')).sum()
  11. Out[308]:
  12. 2014-01-01 0
  13. 2014-01-02 1
  14. 2014-01-03 2
  15. 2014-01-04 3
  16. 2014-01-05 4
  17. ..
  18. 2014-04-06 95
  19. 2014-04-07 96
  20. 2014-04-08 97
  21. 2014-04-09 98
  22. 2014-04-10 99
  23. Length: 100, dtype: int64

Aggregation

Similar to the aggregating API, groupby API, and the window functions API,a Resampler can be selectively resampled.

Resampling a DataFrame, the default will be to act on all columns with the same function.

  1. In [309]: df = pd.DataFrame(np.random.randn(1000, 3),
  2. .....: index=pd.date_range('1/1/2012', freq='S', periods=1000),
  3. .....: columns=['A', 'B', 'C'])
  4. .....:
  5.  
  6. In [310]: r = df.resample('3T')
  7.  
  8. In [311]: r.mean()
  9. Out[311]:
  10. A B C
  11. 2012-01-01 00:00:00 -0.033823 -0.121514 -0.081447
  12. 2012-01-01 00:03:00 0.056909 0.146731 -0.024320
  13. 2012-01-01 00:06:00 -0.058837 0.047046 -0.052021
  14. 2012-01-01 00:09:00 0.063123 -0.026158 -0.066533
  15. 2012-01-01 00:12:00 0.186340 -0.003144 0.074752
  16. 2012-01-01 00:15:00 -0.085954 -0.016287 -0.050046

We can select a specific column or columns using standard getitem.

  1. In [312]: r['A'].mean()
  2. Out[312]:
  3. 2012-01-01 00:00:00 -0.033823
  4. 2012-01-01 00:03:00 0.056909
  5. 2012-01-01 00:06:00 -0.058837
  6. 2012-01-01 00:09:00 0.063123
  7. 2012-01-01 00:12:00 0.186340
  8. 2012-01-01 00:15:00 -0.085954
  9. Freq: 3T, Name: A, dtype: float64
  10.  
  11. In [313]: r[['A', 'B']].mean()
  12. Out[313]:
  13. A B
  14. 2012-01-01 00:00:00 -0.033823 -0.121514
  15. 2012-01-01 00:03:00 0.056909 0.146731
  16. 2012-01-01 00:06:00 -0.058837 0.047046
  17. 2012-01-01 00:09:00 0.063123 -0.026158
  18. 2012-01-01 00:12:00 0.186340 -0.003144
  19. 2012-01-01 00:15:00 -0.085954 -0.016287

You can pass a list or dict of functions to do aggregation with, outputting a DataFrame:

  1. In [314]: r['A'].agg([np.sum, np.mean, np.std])
  2. Out[314]:
  3. sum mean std
  4. 2012-01-01 00:00:00 -6.088060 -0.033823 1.043263
  5. 2012-01-01 00:03:00 10.243678 0.056909 1.058534
  6. 2012-01-01 00:06:00 -10.590584 -0.058837 0.949264
  7. 2012-01-01 00:09:00 11.362228 0.063123 1.028096
  8. 2012-01-01 00:12:00 33.541257 0.186340 0.884586
  9. 2012-01-01 00:15:00 -8.595393 -0.085954 1.035476

On a resampled DataFrame, you can pass a list of functions to apply to eachcolumn, which produces an aggregated result with a hierarchical index:

  1. In [315]: r.agg([np.sum, np.mean])
  2. Out[315]:
  3. A B C
  4. sum mean sum mean sum mean
  5. 2012-01-01 00:00:00 -6.088060 -0.033823 -21.872530 -0.121514 -14.660515 -0.081447
  6. 2012-01-01 00:03:00 10.243678 0.056909 26.411633 0.146731 -4.377642 -0.024320
  7. 2012-01-01 00:06:00 -10.590584 -0.058837 8.468289 0.047046 -9.363825 -0.052021
  8. 2012-01-01 00:09:00 11.362228 0.063123 -4.708526 -0.026158 -11.975895 -0.066533
  9. 2012-01-01 00:12:00 33.541257 0.186340 -0.565895 -0.003144 13.455299 0.074752
  10. 2012-01-01 00:15:00 -8.595393 -0.085954 -1.628689 -0.016287 -5.004580 -0.050046

By passing a dict to aggregate you can apply a different aggregation to thecolumns of a DataFrame:

  1. In [316]: r.agg({'A': np.sum,
  2. .....: 'B': lambda x: np.std(x, ddof=1)})
  3. .....:
  4. Out[316]:
  5. A B
  6. 2012-01-01 00:00:00 -6.088060 1.001294
  7. 2012-01-01 00:03:00 10.243678 1.074597
  8. 2012-01-01 00:06:00 -10.590584 0.987309
  9. 2012-01-01 00:09:00 11.362228 0.944953
  10. 2012-01-01 00:12:00 33.541257 1.095025
  11. 2012-01-01 00:15:00 -8.595393 1.035312

The function names can also be strings. In order for a string to be valid itmust be implemented on the resampled object:

  1. In [317]: r.agg({'A': 'sum', 'B': 'std'})
  2. Out[317]:
  3. A B
  4. 2012-01-01 00:00:00 -6.088060 1.001294
  5. 2012-01-01 00:03:00 10.243678 1.074597
  6. 2012-01-01 00:06:00 -10.590584 0.987309
  7. 2012-01-01 00:09:00 11.362228 0.944953
  8. 2012-01-01 00:12:00 33.541257 1.095025
  9. 2012-01-01 00:15:00 -8.595393 1.035312

Furthermore, you can also specify multiple aggregation functions for each column separately.

  1. In [318]: r.agg({'A': ['sum', 'std'], 'B': ['mean', 'std']})
  2. Out[318]:
  3. A B
  4. sum std mean std
  5. 2012-01-01 00:00:00 -6.088060 1.043263 -0.121514 1.001294
  6. 2012-01-01 00:03:00 10.243678 1.058534 0.146731 1.074597
  7. 2012-01-01 00:06:00 -10.590584 0.949264 0.047046 0.987309
  8. 2012-01-01 00:09:00 11.362228 1.028096 -0.026158 0.944953
  9. 2012-01-01 00:12:00 33.541257 0.884586 -0.003144 1.095025
  10. 2012-01-01 00:15:00 -8.595393 1.035476 -0.016287 1.035312

If a DataFrame does not have a datetimelike index, but instead you wantto resample based on datetimelike column in the frame, it can passed to theon keyword.

  1. In [319]: df = pd.DataFrame({'date': pd.date_range('2015-01-01', freq='W', periods=5),
  2. .....: 'a': np.arange(5)},
  3. .....: index=pd.MultiIndex.from_arrays([
  4. .....: [1, 2, 3, 4, 5],
  5. .....: pd.date_range('2015-01-01', freq='W', periods=5)],
  6. .....: names=['v', 'd']))
  7. .....:
  8.  
  9. In [320]: df
  10. Out[320]:
  11. date a
  12. v d
  13. 1 2015-01-04 2015-01-04 0
  14. 2 2015-01-11 2015-01-11 1
  15. 3 2015-01-18 2015-01-18 2
  16. 4 2015-01-25 2015-01-25 3
  17. 5 2015-02-01 2015-02-01 4
  18.  
  19. In [321]: df.resample('M', on='date').sum()
  20. Out[321]:
  21. a
  22. date
  23. 2015-01-31 6
  24. 2015-02-28 4

Similarly, if you instead want to resample by a datetimelikelevel of MultiIndex, its name or location can be passed to thelevel keyword.

  1. In [322]: df.resample('M', level='d').sum()
  2. Out[322]:
  3. a
  4. d
  5. 2015-01-31 6
  6. 2015-02-28 4

Iterating through groups

With the Resampler object in hand, iterating through the grouped data is verynatural and functions similarly to itertools.groupby():

  1. In [323]: small = pd.Series(
  2. .....: range(6),
  3. .....: index=pd.to_datetime(['2017-01-01T00:00:00',
  4. .....: '2017-01-01T00:30:00',
  5. .....: '2017-01-01T00:31:00',
  6. .....: '2017-01-01T01:00:00',
  7. .....: '2017-01-01T03:00:00',
  8. .....: '2017-01-01T03:05:00'])
  9. .....: )
  10. .....:
  11.  
  12. In [324]: resampled = small.resample('H')
  13.  
  14. In [325]: for name, group in resampled:
  15. .....: print("Group: ", name)
  16. .....: print("-" * 27)
  17. .....: print(group, end="\n\n")
  18. .....:
  19. Group: 2017-01-01 00:00:00
  20. ---------------------------
  21. 2017-01-01 00:00:00 0
  22. 2017-01-01 00:30:00 1
  23. 2017-01-01 00:31:00 2
  24. dtype: int64
  25.  
  26. Group: 2017-01-01 01:00:00
  27. ---------------------------
  28. 2017-01-01 01:00:00 3
  29. dtype: int64
  30.  
  31. Group: 2017-01-01 02:00:00
  32. ---------------------------
  33. Series([], dtype: int64)
  34.  
  35. Group: 2017-01-01 03:00:00
  36. ---------------------------
  37. 2017-01-01 03:00:00 4
  38. 2017-01-01 03:05:00 5
  39. dtype: int64

See Iterating through groups or Resampler.iter for more.

Time span representation

Regular intervals of time are represented by Period objects in pandas whilesequences of Period objects are collected in a PeriodIndex, which canbe created with the convenience function period_range.

Period

A Period represents a span of time (e.g., a day, a month, a quarter, etc).You can specify the span via freq keyword using a frequency alias like below.Because freq represents a span of Period, it cannot be negative like “-3D”.

  1. In [326]: pd.Period('2012', freq='A-DEC')
  2. Out[326]: Period('2012', 'A-DEC')
  3.  
  4. In [327]: pd.Period('2012-1-1', freq='D')
  5. Out[327]: Period('2012-01-01', 'D')
  6.  
  7. In [328]: pd.Period('2012-1-1 19:00', freq='H')
  8. Out[328]: Period('2012-01-01 19:00', 'H')
  9.  
  10. In [329]: pd.Period('2012-1-1 19:00', freq='5H')
  11. Out[329]: Period('2012-01-01 19:00', '5H')

Adding and subtracting integers from periods shifts the period by its ownfrequency. Arithmetic is not allowed between Period with different freq (span).

  1. In [330]: p = pd.Period('2012', freq='A-DEC')
  2.  
  3. In [331]: p + 1
  4. Out[331]: Period('2013', 'A-DEC')
  5.  
  6. In [332]: p - 3
  7. Out[332]: Period('2009', 'A-DEC')
  8.  
  9. In [333]: p = pd.Period('2012-01', freq='2M')
  10.  
  11. In [334]: p + 2
  12. Out[334]: Period('2012-05', '2M')
  13.  
  14. In [335]: p - 1
  15. Out[335]: Period('2011-11', '2M')
  16.  
  17. In [336]: p == pd.Period('2012-01', freq='3M')
  18. ---------------------------------------------------------------------------
  19. IncompatibleFrequency Traceback (most recent call last)
  20. <ipython-input-336-4b67dc0b596c> in <module>
  21. ----> 1 p == pd.Period('2012-01', freq='3M')
  22.  
  23. /pandas/pandas/_libs/tslibs/period.pyx in pandas._libs.tslibs.period._Period.__richcmp__()
  24.  
  25. IncompatibleFrequency: Input has different freq=3M from Period(freq=2M)

If Period freq is daily or higher (D, H, T, S, L, U, N), offsets and timedelta-like can be added if the result can have the same freq. Otherwise, ValueError will be raised.

  1. In [337]: p = pd.Period('2014-07-01 09:00', freq='H')
  2.  
  3. In [338]: p + pd.offsets.Hour(2)
  4. Out[338]: Period('2014-07-01 11:00', 'H')
  5.  
  6. In [339]: p + datetime.timedelta(minutes=120)
  7. Out[339]: Period('2014-07-01 11:00', 'H')
  8.  
  9. In [340]: p + np.timedelta64(7200, 's')
  10. Out[340]: Period('2014-07-01 11:00', 'H')
  1. In [1]: p + pd.offsets.Minute(5)
  2. Traceback
  3. ...
  4. ValueError: Input has different freq from Period(freq=H)

If Period has other frequencies, only the same offsets can be added. Otherwise, ValueError will be raised.

  1. In [341]: p = pd.Period('2014-07', freq='M')
  2.  
  3. In [342]: p + pd.offsets.MonthEnd(3)
  4. Out[342]: Period('2014-10', 'M')
  1. In [1]: p + pd.offsets.MonthBegin(3)
  2. Traceback
  3. ...
  4. ValueError: Input has different freq from Period(freq=M)

Taking the difference of Period instances with the same frequency willreturn the number of frequency units between them:

  1. In [343]: pd.Period('2012', freq='A-DEC') - pd.Period('2002', freq='A-DEC')
  2. Out[343]: <10 * YearEnds: month=12>

PeriodIndex and period_range

Regular sequences of Period objects can be collected in a PeriodIndex,which can be constructed using the period_range convenience function:

  1. In [344]: prng = pd.period_range('1/1/2011', '1/1/2012', freq='M')
  2.  
  3. In [345]: prng
  4. Out[345]:
  5. PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05', '2011-06',
  6. '2011-07', '2011-08', '2011-09', '2011-10', '2011-11', '2011-12',
  7. '2012-01'],
  8. dtype='period[M]', freq='M')

The PeriodIndex constructor can also be used directly:

  1. In [346]: pd.PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')
  2. Out[346]: PeriodIndex(['2011-01', '2011-02', '2011-03'], dtype='period[M]', freq='M')

Passing multiplied frequency outputs a sequence of Period whichhas multiplied span.

  1. In [347]: pd.period_range(start='2014-01', freq='3M', periods=4)
  2. Out[347]: PeriodIndex(['2014-01', '2014-04', '2014-07', '2014-10'], dtype='period[3M]', freq='3M')

If start or end are Period objects, they will be used as anchorendpoints for a PeriodIndex with frequency matching that of thePeriodIndex constructor.

  1. In [348]: pd.period_range(start=pd.Period('2017Q1', freq='Q'),
  2. .....: end=pd.Period('2017Q2', freq='Q'), freq='M')
  3. .....:
  4. Out[348]: PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], dtype='period[M]', freq='M')

Just like DatetimeIndex, a PeriodIndex can also be used to index pandasobjects:

  1. In [349]: ps = pd.Series(np.random.randn(len(prng)), prng)
  2.  
  3. In [350]: ps
  4. Out[350]:
  5. 2011-01 -2.916901
  6. 2011-02 0.514474
  7. 2011-03 1.346470
  8. 2011-04 0.816397
  9. 2011-05 2.258648
  10. 2011-06 0.494789
  11. 2011-07 0.301239
  12. 2011-08 0.464776
  13. 2011-09 -1.393581
  14. 2011-10 0.056780
  15. 2011-11 0.197035
  16. 2011-12 2.261385
  17. 2012-01 -0.329583
  18. Freq: M, dtype: float64

PeriodIndex supports addition and subtraction with the same rule as Period.

  1. In [351]: idx = pd.period_range('2014-07-01 09:00', periods=5, freq='H')
  2.  
  3. In [352]: idx
  4. Out[352]:
  5. PeriodIndex(['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
  6. '2014-07-01 12:00', '2014-07-01 13:00'],
  7. dtype='period[H]', freq='H')
  8.  
  9. In [353]: idx + pd.offsets.Hour(2)
  10. Out[353]:
  11. PeriodIndex(['2014-07-01 11:00', '2014-07-01 12:00', '2014-07-01 13:00',
  12. '2014-07-01 14:00', '2014-07-01 15:00'],
  13. dtype='period[H]', freq='H')
  14.  
  15. In [354]: idx = pd.period_range('2014-07', periods=5, freq='M')
  16.  
  17. In [355]: idx
  18. Out[355]: PeriodIndex(['2014-07', '2014-08', '2014-09', '2014-10', '2014-11'], dtype='period[M]', freq='M')
  19.  
  20. In [356]: idx + pd.offsets.MonthEnd(3)
  21. Out[356]: PeriodIndex(['2014-10', '2014-11', '2014-12', '2015-01', '2015-02'], dtype='period[M]', freq='M')

PeriodIndex has its own dtype named period, refer to Period Dtypes.

Period dtypes

New in version 0.19.0.

PeriodIndex has a custom period dtype. This is a pandas extensiondtype similar to the timezone aware dtype (datetime64[ns, tz]).

The period dtype holds the freq attribute and is represented withperiod[freq] like period[D] or period[M], using frequency strings.

  1. In [357]: pi = pd.period_range('2016-01-01', periods=3, freq='M')
  2.  
  3. In [358]: pi
  4. Out[358]: PeriodIndex(['2016-01', '2016-02', '2016-03'], dtype='period[M]', freq='M')
  5.  
  6. In [359]: pi.dtype
  7. Out[359]: period[M]

The period dtype can be used in .astype(…). It allows one to change thefreq of a PeriodIndex like .asfreq() and convert aDatetimeIndex to PeriodIndex like to_period():

  1. # change monthly freq to daily freq
  2. In [360]: pi.astype('period[D]')
  3. Out[360]: PeriodIndex(['2016-01-31', '2016-02-29', '2016-03-31'], dtype='period[D]', freq='D')
  4.  
  5. # convert to DatetimeIndex
  6. In [361]: pi.astype('datetime64[ns]')
  7. Out[361]: DatetimeIndex(['2016-01-01', '2016-02-01', '2016-03-01'], dtype='datetime64[ns]', freq='MS')
  8.  
  9. # convert to PeriodIndex
  10. In [362]: dti = pd.date_range('2011-01-01', freq='M', periods=3)
  11.  
  12. In [363]: dti
  13. Out[363]: DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31'], dtype='datetime64[ns]', freq='M')
  14.  
  15. In [364]: dti.astype('period[M]')
  16. Out[364]: PeriodIndex(['2011-01', '2011-02', '2011-03'], dtype='period[M]', freq='M')

PeriodIndex partial string indexing

You can pass in dates and strings to Series and DataFrame with PeriodIndex, in the same manner as DatetimeIndex. For details, refer to DatetimeIndex Partial String Indexing.

  1. In [365]: ps['2011-01']
  2. Out[365]: -2.9169013294054507
  3.  
  4. In [366]: ps[datetime.datetime(2011, 12, 25):]
  5. Out[366]:
  6. 2011-12 2.261385
  7. 2012-01 -0.329583
  8. Freq: M, dtype: float64
  9.  
  10. In [367]: ps['10/31/2011':'12/31/2011']
  11. Out[367]:
  12. 2011-10 0.056780
  13. 2011-11 0.197035
  14. 2011-12 2.261385
  15. Freq: M, dtype: float64

Passing a string representing a lower frequency than PeriodIndex returns partial sliced data.

  1. In [368]: ps['2011']
  2. Out[368]:
  3. 2011-01 -2.916901
  4. 2011-02 0.514474
  5. 2011-03 1.346470
  6. 2011-04 0.816397
  7. 2011-05 2.258648
  8. 2011-06 0.494789
  9. 2011-07 0.301239
  10. 2011-08 0.464776
  11. 2011-09 -1.393581
  12. 2011-10 0.056780
  13. 2011-11 0.197035
  14. 2011-12 2.261385
  15. Freq: M, dtype: float64
  16.  
  17. In [369]: dfp = pd.DataFrame(np.random.randn(600, 1),
  18. .....: columns=['A'],
  19. .....: index=pd.period_range('2013-01-01 9:00',
  20. .....: periods=600,
  21. .....: freq='T'))
  22. .....:
  23.  
  24. In [370]: dfp
  25. Out[370]:
  26. A
  27. 2013-01-01 09:00 -0.538468
  28. 2013-01-01 09:01 -1.365819
  29. 2013-01-01 09:02 -0.969051
  30. 2013-01-01 09:03 -0.331152
  31. 2013-01-01 09:04 -0.245334
  32. ... ...
  33. 2013-01-01 18:55 0.522460
  34. 2013-01-01 18:56 0.118710
  35. 2013-01-01 18:57 0.167517
  36. 2013-01-01 18:58 0.922883
  37. 2013-01-01 18:59 1.721104
  38.  
  39. [600 rows x 1 columns]
  40.  
  41. In [371]: dfp['2013-01-01 10H']
  42. Out[371]:
  43. A
  44. 2013-01-01 10:00 -0.308975
  45. 2013-01-01 10:01 0.542520
  46. 2013-01-01 10:02 1.061068
  47. 2013-01-01 10:03 0.754005
  48. 2013-01-01 10:04 0.352933
  49. ... ...
  50. 2013-01-01 10:55 -0.865621
  51. 2013-01-01 10:56 -1.167818
  52. 2013-01-01 10:57 -2.081748
  53. 2013-01-01 10:58 -0.527146
  54. 2013-01-01 10:59 0.802298
  55.  
  56. [60 rows x 1 columns]

As with DatetimeIndex, the endpoints will be included in the result. The example below slices data starting from 10:00 to 11:59.

  1. In [372]: dfp['2013-01-01 10H':'2013-01-01 11H']
  2. Out[372]:
  3. A
  4. 2013-01-01 10:00 -0.308975
  5. 2013-01-01 10:01 0.542520
  6. 2013-01-01 10:02 1.061068
  7. 2013-01-01 10:03 0.754005
  8. 2013-01-01 10:04 0.352933
  9. ... ...
  10. 2013-01-01 11:55 -0.590204
  11. 2013-01-01 11:56 1.539990
  12. 2013-01-01 11:57 -1.224826
  13. 2013-01-01 11:58 0.578798
  14. 2013-01-01 11:59 -0.685496
  15.  
  16. [120 rows x 1 columns]

Frequency conversion and resampling with PeriodIndex

The frequency of Period and PeriodIndex can be converted via the asfreqmethod. Let’s start with the fiscal year 2011, ending in December:

  1. In [373]: p = pd.Period('2011', freq='A-DEC')
  2.  
  3. In [374]: p
  4. Out[374]: Period('2011', 'A-DEC')

We can convert it to a monthly frequency. Using the how parameter, we canspecify whether to return the starting or ending month:

  1. In [375]: p.asfreq('M', how='start')
  2. Out[375]: Period('2011-01', 'M')
  3.  
  4. In [376]: p.asfreq('M', how='end')
  5. Out[376]: Period('2011-12', 'M')

The shorthands ‘s’ and ‘e’ are provided for convenience:

  1. In [377]: p.asfreq('M', 's')
  2. Out[377]: Period('2011-01', 'M')
  3.  
  4. In [378]: p.asfreq('M', 'e')
  5. Out[378]: Period('2011-12', 'M')

Converting to a “super-period” (e.g., annual frequency is a super-period ofquarterly frequency) automatically returns the super-period that includes theinput period:

  1. In [379]: p = pd.Period('2011-12', freq='M')
  2.  
  3. In [380]: p.asfreq('A-NOV')
  4. Out[380]: Period('2012', 'A-NOV')

Note that since we converted to an annual frequency that ends the year inNovember, the monthly period of December 2011 is actually in the 2012 A-NOVperiod.

Period conversions with anchored frequencies are particularly useful forworking with various quarterly data common to economics, business, and otherfields. Many organizations define quarters relative to the month in which theirfiscal year starts and ends. Thus, first quarter of 2011 could start in 2010 ora few months into 2011. Via anchored frequencies, pandas works for all quarterlyfrequencies Q-JAN through Q-DEC.

Q-DEC define regular calendar quarters:

  1. In [381]: p = pd.Period('2012Q1', freq='Q-DEC')
  2.  
  3. In [382]: p.asfreq('D', 's')
  4. Out[382]: Period('2012-01-01', 'D')
  5.  
  6. In [383]: p.asfreq('D', 'e')
  7. Out[383]: Period('2012-03-31', 'D')

Q-MAR defines fiscal year end in March:

  1. In [384]: p = pd.Period('2011Q4', freq='Q-MAR')
  2.  
  3. In [385]: p.asfreq('D', 's')
  4. Out[385]: Period('2011-01-01', 'D')
  5.  
  6. In [386]: p.asfreq('D', 'e')
  7. Out[386]: Period('2011-03-31', 'D')

Converting between representations

Timestamped data can be converted to PeriodIndex-ed data using to_periodand vice-versa using to_timestamp:

  1. In [387]: rng = pd.date_range('1/1/2012', periods=5, freq='M')
  2.  
  3. In [388]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
  4.  
  5. In [389]: ts
  6. Out[389]:
  7. 2012-01-31 1.931253
  8. 2012-02-29 -0.184594
  9. 2012-03-31 0.249656
  10. 2012-04-30 -0.978151
  11. 2012-05-31 -0.873389
  12. Freq: M, dtype: float64
  13.  
  14. In [390]: ps = ts.to_period()
  15.  
  16. In [391]: ps
  17. Out[391]:
  18. 2012-01 1.931253
  19. 2012-02 -0.184594
  20. 2012-03 0.249656
  21. 2012-04 -0.978151
  22. 2012-05 -0.873389
  23. Freq: M, dtype: float64
  24.  
  25. In [392]: ps.to_timestamp()
  26. Out[392]:
  27. 2012-01-01 1.931253
  28. 2012-02-01 -0.184594
  29. 2012-03-01 0.249656
  30. 2012-04-01 -0.978151
  31. 2012-05-01 -0.873389
  32. Freq: MS, dtype: float64

Remember that ‘s’ and ‘e’ can be used to return the timestamps at the start orend of the period:

  1. In [393]: ps.to_timestamp('D', how='s')
  2. Out[393]:
  3. 2012-01-01 1.931253
  4. 2012-02-01 -0.184594
  5. 2012-03-01 0.249656
  6. 2012-04-01 -0.978151
  7. 2012-05-01 -0.873389
  8. Freq: MS, dtype: float64

Converting between period and timestamp enables some convenient arithmeticfunctions to be used. In the following example, we convert a quarterlyfrequency with year ending in November to 9am of the end of the month followingthe quarter end:

  1. In [394]: prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
  2.  
  3. In [395]: ts = pd.Series(np.random.randn(len(prng)), prng)
  4.  
  5. In [396]: ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
  6.  
  7. In [397]: ts.head()
  8. Out[397]:
  9. 1990-03-01 09:00 -0.109291
  10. 1990-06-01 09:00 -0.637235
  11. 1990-09-01 09:00 -1.735925
  12. 1990-12-01 09:00 2.096946
  13. 1991-03-01 09:00 -1.039926
  14. Freq: H, dtype: float64

Representing out-of-bounds spans

If you have data that is outside of the Timestamp bounds, see Timestamp limitations,then you can use a PeriodIndex and/or Series of Periods to do computations.

  1. In [398]: span = pd.period_range('1215-01-01', '1381-01-01', freq='D')
  2.  
  3. In [399]: span
  4. Out[399]:
  5. PeriodIndex(['1215-01-01', '1215-01-02', '1215-01-03', '1215-01-04',
  6. '1215-01-05', '1215-01-06', '1215-01-07', '1215-01-08',
  7. '1215-01-09', '1215-01-10',
  8. ...
  9. '1380-12-23', '1380-12-24', '1380-12-25', '1380-12-26',
  10. '1380-12-27', '1380-12-28', '1380-12-29', '1380-12-30',
  11. '1380-12-31', '1381-01-01'],
  12. dtype='period[D]', length=60632, freq='D')

To convert from an int64 based YYYYMMDD representation.

  1. In [400]: s = pd.Series([20121231, 20141130, 99991231])
  2.  
  3. In [401]: s
  4. Out[401]:
  5. 0 20121231
  6. 1 20141130
  7. 2 99991231
  8. dtype: int64
  9.  
  10. In [402]: def conv(x):
  11. .....: return pd.Period(year=x // 10000, month=x // 100 % 100,
  12. .....: day=x % 100, freq='D')
  13. .....:
  14.  
  15. In [403]: s.apply(conv)
  16. Out[403]:
  17. 0 2012-12-31
  18. 1 2014-11-30
  19. 2 9999-12-31
  20. dtype: period[D]
  21.  
  22. In [404]: s.apply(conv)[2]
  23. Out[404]: Period('9999-12-31', 'D')

These can easily be converted to a PeriodIndex:

  1. In [405]: span = pd.PeriodIndex(s.apply(conv))
  2.  
  3. In [406]: span
  4. Out[406]: PeriodIndex(['2012-12-31', '2014-11-30', '9999-12-31'], dtype='period[D]', freq='D')

Time zone handling

pandas provides rich support for working with timestamps in different timezones using the pytz and dateutil libraries or class:_datetime.timezone_objects from the standard library.

Working with time zones

By default, pandas objects are time zone unaware:

  1. In [407]: rng = pd.date_range('3/6/2012 00:00', periods=15, freq='D')
  2.  
  3. In [408]: rng.tz is None
  4. Out[408]: True

To localize these dates to a time zone (assign a particular time zone to a naive date),you can use the tz_localize method or the tz keyword argument indate_range(), Timestamp, or DatetimeIndex.You can either pass pytz or dateutil time zone objects or Olson time zone database strings.Olson time zone strings will return pytz time zone objects by default.To return dateutil time zone objects, append dateutil/ before the string.

  • In pytz you can find a list of common (and less common) time zones usingfrom pytz import common_timezones, all_timezones.
  • dateutil uses the OS time zones so there isn’t a fixed list available. Forcommon zones, the names are the same as pytz.
  1. In [409]: import dateutil
  2.  
  3. # pytz
  4. In [410]: rng_pytz = pd.date_range('3/6/2012 00:00', periods=3, freq='D',
  5. .....: tz='Europe/London')
  6. .....:
  7.  
  8. In [411]: rng_pytz.tz
  9. Out[411]: <DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>
  10.  
  11. # dateutil
  12. In [412]: rng_dateutil = pd.date_range('3/6/2012 00:00', periods=3, freq='D')
  13.  
  14. In [413]: rng_dateutil = rng_dateutil.tz_localize('dateutil/Europe/London')
  15.  
  16. In [414]: rng_dateutil.tz
  17. Out[414]: tzfile('/usr/share/zoneinfo/Europe/London')
  18.  
  19. # dateutil - utc special case
  20. In [415]: rng_utc = pd.date_range('3/6/2012 00:00', periods=3, freq='D',
  21. .....: tz=dateutil.tz.tzutc())
  22. .....:
  23.  
  24. In [416]: rng_utc.tz
  25. Out[416]: tzutc()

New in version 0.25.0.

  1. # datetime.timezone
  2. In [417]: rng_utc = pd.date_range('3/6/2012 00:00', periods=3, freq='D',
  3. .....: tz=datetime.timezone.utc)
  4. .....:
  5.  
  6. In [418]: rng_utc.tz
  7. Out[418]: datetime.timezone.utc

Note that the UTC time zone is a special case in dateutil and should be constructed explicitlyas an instance of dateutil.tz.tzutc. You can also construct other timezones objects explicitly first.

  1. In [419]: import pytz
  2.  
  3. # pytz
  4. In [420]: tz_pytz = pytz.timezone('Europe/London')
  5.  
  6. In [421]: rng_pytz = pd.date_range('3/6/2012 00:00', periods=3, freq='D')
  7.  
  8. In [422]: rng_pytz = rng_pytz.tz_localize(tz_pytz)
  9.  
  10. In [423]: rng_pytz.tz == tz_pytz
  11. Out[423]: True
  12.  
  13. # dateutil
  14. In [424]: tz_dateutil = dateutil.tz.gettz('Europe/London')
  15.  
  16. In [425]: rng_dateutil = pd.date_range('3/6/2012 00:00', periods=3, freq='D',
  17. .....: tz=tz_dateutil)
  18. .....:
  19.  
  20. In [426]: rng_dateutil.tz == tz_dateutil
  21. Out[426]: True

To convert a time zone aware pandas object from one time zone to another,you can use the tz_convert method.

  1. In [427]: rng_pytz.tz_convert('US/Eastern')
  2. Out[427]:
  3. DatetimeIndex(['2012-03-05 19:00:00-05:00', '2012-03-06 19:00:00-05:00',
  4. '2012-03-07 19:00:00-05:00'],
  5. dtype='datetime64[ns, US/Eastern]', freq='D')

Note

When using pytz time zones, DatetimeIndex will construct a differenttime zone object than a Timestamp for the same time zone input. A DatetimeIndexcan hold a collection of Timestamp objects that may have different UTC offsets and cannot besuccinctly represented by one pytz time zone instance while one Timestamprepresents one point in time with a specific UTC offset.

  1. In [428]: dti = pd.date_range('2019-01-01', periods=3, freq='D', tz='US/Pacific')
  2.  
  3. In [429]: dti.tz
  4. Out[429]: <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>
  5.  
  6. In [430]: ts = pd.Timestamp('2019-01-01', tz='US/Pacific')
  7.  
  8. In [431]: ts.tz
  9. Out[431]: <DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>

Warning

Be wary of conversions between libraries. For some time zones, pytz and dateutil have differentdefinitions of the zone. This is more of a problem for unusual time zones than for‘standard’ zones like US/Eastern.

Warning

Be aware that a time zone definition across versions of time zone libraries may notbe considered equal. This may cause problems when working with stored data thatis localized using one version and operated on with a different version.See here for how to handle such a situation.

Warning

For pytz time zones, it is incorrect to pass a time zone object directly intothe datetime.datetime constructor(e.g., datetime.datetime(2011, 1, 1, tz=pytz.timezone('US/Eastern')).Instead, the datetime needs to be localized using the localize methodon the pytz time zone object.

Under the hood, all timestamps are stored in UTC. Values from a time zone awareDatetimeIndex or Timestamp will have their fields (day, hour, minute, etc.)localized to the time zone. However, timestamps with the same UTC value arestill considered to be equal even if they are in different time zones:

  1. In [432]: rng_eastern = rng_utc.tz_convert('US/Eastern')
  2.  
  3. In [433]: rng_berlin = rng_utc.tz_convert('Europe/Berlin')
  4.  
  5. In [434]: rng_eastern[2]
  6. Out[434]: Timestamp('2012-03-07 19:00:00-0500', tz='US/Eastern', freq='D')
  7.  
  8. In [435]: rng_berlin[2]
  9. Out[435]: Timestamp('2012-03-08 01:00:00+0100', tz='Europe/Berlin', freq='D')
  10.  
  11. In [436]: rng_eastern[2] == rng_berlin[2]
  12. Out[436]: True

Operations between Series in different time zones will yield UTCSeries, aligning the data on the UTC timestamps:

  1. In [437]: ts_utc = pd.Series(range(3), pd.date_range('20130101', periods=3, tz='UTC'))
  2.  
  3. In [438]: eastern = ts_utc.tz_convert('US/Eastern')
  4.  
  5. In [439]: berlin = ts_utc.tz_convert('Europe/Berlin')
  6.  
  7. In [440]: result = eastern + berlin
  8.  
  9. In [441]: result
  10. Out[441]:
  11. 2013-01-01 00:00:00+00:00 0
  12. 2013-01-02 00:00:00+00:00 2
  13. 2013-01-03 00:00:00+00:00 4
  14. Freq: D, dtype: int64
  15.  
  16. In [442]: result.index
  17. Out[442]:
  18. DatetimeIndex(['2013-01-01 00:00:00+00:00', '2013-01-02 00:00:00+00:00',
  19. '2013-01-03 00:00:00+00:00'],
  20. dtype='datetime64[ns, UTC]', freq='D')

To remove time zone information, use tz_localize(None) or tz_convert(None).tz_localize(None) will remove the time zone yielding the local time representation.tz_convert(None) will remove the time zone after converting to UTC time.

  1. In [443]: didx = pd.date_range(start='2014-08-01 09:00', freq='H',
  2. .....: periods=3, tz='US/Eastern')
  3. .....:
  4.  
  5. In [444]: didx
  6. Out[444]:
  7. DatetimeIndex(['2014-08-01 09:00:00-04:00', '2014-08-01 10:00:00-04:00',
  8. '2014-08-01 11:00:00-04:00'],
  9. dtype='datetime64[ns, US/Eastern]', freq='H')
  10.  
  11. In [445]: didx.tz_localize(None)
  12. Out[445]:
  13. DatetimeIndex(['2014-08-01 09:00:00', '2014-08-01 10:00:00',
  14. '2014-08-01 11:00:00'],
  15. dtype='datetime64[ns]', freq='H')
  16.  
  17. In [446]: didx.tz_convert(None)
  18. Out[446]:
  19. DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
  20. '2014-08-01 15:00:00'],
  21. dtype='datetime64[ns]', freq='H')
  22.  
  23. # tz_convert(None) is identical to tz_convert('UTC').tz_localize(None)
  24. In [447]: didx.tz_convert('UTC').tz_localize(None)
  25. Out[447]:
  26. DatetimeIndex(['2014-08-01 13:00:00', '2014-08-01 14:00:00',
  27. '2014-08-01 15:00:00'],
  28. dtype='datetime64[ns]', freq='H')

Ambiguous times when localizing

tz_localize may not be able to determine the UTC offset of a timestampbecause daylight savings time (DST) in a local time zone causes some times to occurtwice within one day (“clocks fall back”). The following options are available:

  • 'raise': Raises a pytz.AmbiguousTimeError (the default behavior)
  • 'infer': Attempt to determine the correct offset base on the monotonicity of the timestamps
  • 'NaT': Replaces ambiguous times with NaT
  • bool: True represents a DST time, False represents non-DST time. An array-like of bool values is supported for a sequence of times.
  1. In [448]: rng_hourly = pd.DatetimeIndex(['11/06/2011 00:00', '11/06/2011 01:00',
  2. .....: '11/06/2011 01:00', '11/06/2011 02:00'])
  3. .....:

This will fail as there are ambiguous times ('11/06/2011 01:00')

  1. In [2]: rng_hourly.tz_localize('US/Eastern')
  2. AmbiguousTimeError: Cannot infer dst time from Timestamp('2011-11-06 01:00:00'), try using the 'ambiguous' argument

Handle these ambiguous times by specifying the following.

  1. In [449]: rng_hourly.tz_localize('US/Eastern', ambiguous='infer')
  2. Out[449]:
  3. DatetimeIndex(['2011-11-06 00:00:00-04:00', '2011-11-06 01:00:00-04:00',
  4. '2011-11-06 01:00:00-05:00', '2011-11-06 02:00:00-05:00'],
  5. dtype='datetime64[ns, US/Eastern]', freq=None)
  6.  
  7. In [450]: rng_hourly.tz_localize('US/Eastern', ambiguous='NaT')
  8. Out[450]:
  9. DatetimeIndex(['2011-11-06 00:00:00-04:00', 'NaT', 'NaT',
  10. '2011-11-06 02:00:00-05:00'],
  11. dtype='datetime64[ns, US/Eastern]', freq=None)
  12.  
  13. In [451]: rng_hourly.tz_localize('US/Eastern', ambiguous=[True, True, False, False])
  14. Out[451]:
  15. DatetimeIndex(['2011-11-06 00:00:00-04:00', '2011-11-06 01:00:00-04:00',
  16. '2011-11-06 01:00:00-05:00', '2011-11-06 02:00:00-05:00'],
  17. dtype='datetime64[ns, US/Eastern]', freq=None)

Nonexistent times when localizing

A DST transition may also shift the local time ahead by 1 hour creating nonexistentlocal times (“clocks spring forward”). The behavior of localizing a timeseries with nonexistent timescan be controlled by the nonexistent argument. The following options are available:

  • 'raise': Raises a pytz.NonExistentTimeError (the default behavior)
  • 'NaT': Replaces nonexistent times with NaT
  • 'shift_forward': Shifts nonexistent times forward to the closest real time
  • 'shift_backward': Shifts nonexistent times backward to the closest real time
  • timedelta object: Shifts nonexistent times by the timedelta duration
  1. In [452]: dti = pd.date_range(start='2015-03-29 02:30:00', periods=3, freq='H')
  2.  
  3. # 2:30 is a nonexistent time

Localization of nonexistent times will raise an error by default.

  1. In [2]: dti.tz_localize('Europe/Warsaw')
  2. NonExistentTimeError: 2015-03-29 02:30:00

Transform nonexistent times to NaT or shift the times.

  1. In [453]: dti
  2. Out[453]:
  3. DatetimeIndex(['2015-03-29 02:30:00', '2015-03-29 03:30:00',
  4. '2015-03-29 04:30:00'],
  5. dtype='datetime64[ns]', freq='H')
  6.  
  7. In [454]: dti.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
  8. Out[454]:
  9. DatetimeIndex(['2015-03-29 03:00:00+02:00', '2015-03-29 03:30:00+02:00',
  10. '2015-03-29 04:30:00+02:00'],
  11. dtype='datetime64[ns, Europe/Warsaw]', freq='H')
  12.  
  13. In [455]: dti.tz_localize('Europe/Warsaw', nonexistent='shift_backward')
  14. Out[455]:
  15. DatetimeIndex(['2015-03-29 01:59:59.999999999+01:00',
  16. '2015-03-29 03:30:00+02:00',
  17. '2015-03-29 04:30:00+02:00'],
  18. dtype='datetime64[ns, Europe/Warsaw]', freq='H')
  19.  
  20. In [456]: dti.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta(1, unit='H'))
  21. Out[456]:
  22. DatetimeIndex(['2015-03-29 03:30:00+02:00', '2015-03-29 03:30:00+02:00',
  23. '2015-03-29 04:30:00+02:00'],
  24. dtype='datetime64[ns, Europe/Warsaw]', freq='H')
  25.  
  26. In [457]: dti.tz_localize('Europe/Warsaw', nonexistent='NaT')
  27. Out[457]:
  28. DatetimeIndex(['NaT', '2015-03-29 03:30:00+02:00',
  29. '2015-03-29 04:30:00+02:00'],
  30. dtype='datetime64[ns, Europe/Warsaw]', freq='H')

Time zone series operations

A Series with time zone naive values isrepresented with a dtype of datetime64[ns].

  1. In [458]: s_naive = pd.Series(pd.date_range('20130101', periods=3))
  2.  
  3. In [459]: s_naive
  4. Out[459]:
  5. 0 2013-01-01
  6. 1 2013-01-02
  7. 2 2013-01-03
  8. dtype: datetime64[ns]

A Series with a time zone aware values isrepresented with a dtype of datetime64[ns, tz] where tz is the time zone

  1. In [460]: s_aware = pd.Series(pd.date_range('20130101', periods=3, tz='US/Eastern'))
  2.  
  3. In [461]: s_aware
  4. Out[461]:
  5. 0 2013-01-01 00:00:00-05:00
  6. 1 2013-01-02 00:00:00-05:00
  7. 2 2013-01-03 00:00:00-05:00
  8. dtype: datetime64[ns, US/Eastern]

Both of these Series time zone informationcan be manipulated via the .dt accessor, see the dt accessor section.

For example, to localize and convert a naive stamp to time zone aware.

  1. In [462]: s_naive.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
  2. Out[462]:
  3. 0 2012-12-31 19:00:00-05:00
  4. 1 2013-01-01 19:00:00-05:00
  5. 2 2013-01-02 19:00:00-05:00
  6. dtype: datetime64[ns, US/Eastern]

Time zone information can also be manipulated using the astype method.This method can localize and convert time zone naive timestamps orconvert time zone aware timestamps.

  1. # localize and convert a naive time zone
  2. In [463]: s_naive.astype('datetime64[ns, US/Eastern]')
  3. Out[463]:
  4. 0 2012-12-31 19:00:00-05:00
  5. 1 2013-01-01 19:00:00-05:00
  6. 2 2013-01-02 19:00:00-05:00
  7. dtype: datetime64[ns, US/Eastern]
  8.  
  9. # make an aware tz naive
  10. In [464]: s_aware.astype('datetime64[ns]')
  11. Out[464]:
  12. 0 2013-01-01 05:00:00
  13. 1 2013-01-02 05:00:00
  14. 2 2013-01-03 05:00:00
  15. dtype: datetime64[ns]
  16.  
  17. # convert to a new time zone
  18. In [465]: s_aware.astype('datetime64[ns, CET]')
  19. Out[465]:
  20. 0 2013-01-01 06:00:00+01:00
  21. 1 2013-01-02 06:00:00+01:00
  22. 2 2013-01-03 06:00:00+01:00
  23. dtype: datetime64[ns, CET]

Note

Using Series.to_numpy() on a Series, returns a NumPy array of the data.NumPy does not currently support time zones (even though it is printing in the local time zone!),therefore an object array of Timestamps is returned for time zone aware data:

  1. In [466]: s_naive.to_numpy()
  2. Out[466]:
  3. array(['2013-01-01T00:00:00.000000000', '2013-01-02T00:00:00.000000000',
  4. '2013-01-03T00:00:00.000000000'], dtype='datetime64[ns]')
  5.  
  6. In [467]: s_aware.to_numpy()
  7. Out[467]:
  8. array([Timestamp('2013-01-01 00:00:00-0500', tz='US/Eastern', freq='D'),
  9. Timestamp('2013-01-02 00:00:00-0500', tz='US/Eastern', freq='D'),
  10. Timestamp('2013-01-03 00:00:00-0500', tz='US/Eastern', freq='D')],
  11. dtype=object)

By converting to an object array of Timestamps, it preserves the time zoneinformation. For example, when converting back to a Series:

  1. In [468]: pd.Series(s_aware.to_numpy())
  2. Out[468]:
  3. 0 2013-01-01 00:00:00-05:00
  4. 1 2013-01-02 00:00:00-05:00
  5. 2 2013-01-03 00:00:00-05:00
  6. dtype: datetime64[ns, US/Eastern]

However, if you want an actual NumPy datetime64[ns] array (with the valuesconverted to UTC) instead of an array of objects, you can specify thedtype argument:

  1. In [469]: s_aware.to_numpy(dtype='datetime64[ns]')
  2. Out[469]:
  3. array(['2013-01-01T05:00:00.000000000', '2013-01-02T05:00:00.000000000',
  4. '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')