forked from pandas-dev/pandas
/
timeseries.rst
2114 lines (1405 loc) · 65.4 KB
/
timeseries.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.. currentmodule:: pandas
.. _timeseries:
.. ipython:: python
:suppress:
from datetime import datetime, timedelta, time
import numpy as np
import pandas as pd
from pandas import offsets
np.random.seed(123456)
randn = np.random.randn
randint = np.random.randint
np.set_printoptions(precision=4, suppress=True)
pd.options.display.max_rows=15
import dateutil
import pytz
from dateutil.relativedelta import relativedelta
********************************
Time Series / Date functionality
********************************
pandas has proven very successful as a tool for working with time series data,
especially in the financial data analysis space. Using the NumPy ``datetime64`` and ``timedelta64`` dtypes,
we have consolidated a large number of features from other Python libraries like ``scikits.timeseries`` as well as created
a tremendous amount of new functionality for manipulating time series data.
In working with time series data, we will frequently seek to:
- generate sequences of fixed-frequency dates and time spans
- conform or convert time series to a particular frequency
- compute "relative" dates based on various non-standard time increments
(e.g. 5 business days before the last business day of the year), or "roll"
dates forward or backward
pandas provides a relatively compact and self-contained set of tools for
performing the above tasks.
Create a range of dates:
.. ipython:: python
# 72 hours starting with midnight Jan 1st, 2011
rng = pd.date_range('1/1/2011', periods=72, freq='H')
rng[:5]
Index pandas objects with dates:
.. ipython:: python
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts.head()
Change frequency and fill gaps:
.. ipython:: python
# to 45 minute frequency and forward fill
converted = ts.asfreq('45Min', method='pad')
converted.head()
Resample:
.. ipython:: python
# Daily means
ts.resample('D').mean()
.. _timeseries.overview:
Overview
--------
Following table shows the type of time-related classes pandas can handle and
how to create them.
================= =============================== ==================================================
Class Remarks How to create
================= =============================== ==================================================
``Timestamp`` Represents a single time stamp ``to_datetime``, ``Timestamp``
``DatetimeIndex`` Index of ``Timestamp`` ``to_datetime``, ``date_range``, ``DatetimeIndex``
``Period`` Represents a single time span ``Period``
``PeriodIndex`` Index of ``Period`` ``period_range``, ``PeriodIndex``
================= =============================== ==================================================
.. _timeseries.representation:
Time Stamps vs. Time Spans
--------------------------
Time-stamped data is the most basic type of timeseries data that associates
values with points in time. For pandas objects it means using the points in
time.
.. ipython:: python
pd.Timestamp(datetime(2012, 5, 1))
pd.Timestamp('2012-05-01')
pd.Timestamp(2012, 5, 1)
However, in many cases it is more natural to associate things like change
variables with a time span instead. The span represented by ``Period`` can be
specified explicitly, or inferred from datetime string format.
For example:
.. ipython:: python
pd.Period('2011-01')
pd.Period('2012-05', freq='D')
``Timestamp`` and ``Period`` can be the index. Lists of ``Timestamp`` and
``Period`` are automatically coerce to ``DatetimeIndex`` and ``PeriodIndex``
respectively.
.. ipython:: python
dates = [pd.Timestamp('2012-05-01'), pd.Timestamp('2012-05-02'), pd.Timestamp('2012-05-03')]
ts = pd.Series(np.random.randn(3), dates)
type(ts.index)
ts.index
ts
periods = [pd.Period('2012-01'), pd.Period('2012-02'), pd.Period('2012-03')]
ts = pd.Series(np.random.randn(3), periods)
type(ts.index)
ts.index
ts
pandas allows you to capture both representations and
convert between them. Under the hood, pandas represents timestamps using
instances of ``Timestamp`` and sequences of timestamps using instances of
``DatetimeIndex``. For regular time spans, pandas uses ``Period`` objects for
scalar values and ``PeriodIndex`` for sequences of spans. Better support for
irregular intervals with arbitrary start and end points are forth-coming in
future releases.
.. _timeseries.converting:
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 passed
a Series, this returns a Series (with the same index), while a list-like
is converted to a DatetimeIndex:
.. ipython:: python
pd.to_datetime(pd.Series(['Jul 31, 2009', '2010-01-10', None]))
pd.to_datetime(['2005/11/23', '2010.12.31'])
If you use dates which start with the day first (i.e. European style),
you can pass the ``dayfirst`` flag:
.. ipython:: python
pd.to_datetime(['04-01-2012 10:00'], dayfirst=True)
pd.to_datetime(['14-01-2012', '01-14-2012'], dayfirst=True)
.. warning::
You see in the above example that ``dayfirst`` isn't strict, so if a date
can't be parsed with the day being first it will be parsed as if
``dayfirst`` were False.
.. note::
Specifying a ``format`` argument will potentially speed up the conversion
considerably and on versions later then 0.13.0 explicitly specifying
a format string of '%Y%m%d' takes a faster path still.
If you pass a single string to ``to_datetime``, it returns single ``Timestamp``.
Also, ``Timestamp`` can accept the string input.
Note that ``Timestamp`` doesn't accept string parsing option like ``dayfirst``
or ``format``, use ``to_datetime`` if these are required.
.. ipython:: python
pd.to_datetime('2010/11/12')
pd.Timestamp('2010/11/12')
.. versionadded:: 0.18.1
You can also pass a ``DataFrame`` of integer or string columns to assemble into a ``Series`` of ``Timestamps``.
.. ipython:: python
df = pd.DataFrame({'year': [2015, 2016],
'month': [2, 3],
'day': [4, 5],
'hour': [2, 3]})
pd.to_datetime(df)
You can pass only the columns that you need to assemble.
.. ipython:: python
pd.to_datetime(df[['year', 'month', 'day']])
``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
~~~~~~~~~~~~
.. note::
In version 0.17.0, the default for ``to_datetime`` is now ``errors='raise'``, rather than ``errors='ignore'``. This means
that invalid parsing will raise rather that return the original input as in previous versions.
Pass ``errors='coerce'`` to convert invalid data to ``NaT`` (not a time):
Raise when unparseable, this is the default
.. code-block:: ipython
In [2]: pd.to_datetime(['2009/07/31', 'asd'], errors='raise')
ValueError: Unknown string format
Return the original input when unparseable
.. code-block:: ipython
In [4]: pd.to_datetime(['2009/07/31', 'asd'], errors='ignore')
Out[4]: array(['2009/07/31', 'asd'], dtype=object)
Return NaT for input when unparseable
.. code-block:: ipython
In [6]: pd.to_datetime(['2009/07/31', 'asd'], errors='coerce')
Out[6]: DatetimeIndex(['2009-07-31', 'NaT'], dtype='datetime64[ns]', freq=None)
Epoch Timestamps
~~~~~~~~~~~~~~~~
It's also possible to convert integer or float epoch times. The default unit
for these is nanoseconds (since these are how ``Timestamp`` s are stored). However,
often epochs are stored in another ``unit`` which can be specified:
Typical epoch stored units
.. ipython:: python
pd.to_datetime([1349720105, 1349806505, 1349892905,
1349979305, 1350065705], unit='s')
pd.to_datetime([1349720105100, 1349720105200, 1349720105300,
1349720105400, 1349720105500 ], unit='ms')
These *work*, but the results may be unexpected.
.. ipython:: python
pd.to_datetime([1])
pd.to_datetime([1, 3.14], unit='s')
.. note::
Epoch times will be rounded to the nearest nanosecond.
.. _timeseries.daterange:
Generating Ranges of Timestamps
-------------------------------
To generate an index with time stamps, you can use either the DatetimeIndex or
Index constructor and pass in a list of datetime objects:
.. ipython:: python
dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]
# Note the frequency information
index = pd.DatetimeIndex(dates)
index
# Automatically converted to DatetimeIndex
index = pd.Index(dates)
index
Practically, this becomes very cumbersome because we often need a very long
index with a large number of timestamps. If we need timestamps on a regular
frequency, we can use the pandas functions ``date_range`` and ``bdate_range``
to create timestamp indexes.
.. ipython:: python
index = pd.date_range('2000-1-1', periods=1000, freq='M')
index
index = pd.bdate_range('2012-1-1', periods=250)
index
Convenience functions like ``date_range`` and ``bdate_range`` utilize a
variety of frequency aliases. The default frequency for ``date_range`` is a
**calendar day** while the default for ``bdate_range`` is a **business day**
.. ipython:: python
start = datetime(2011, 1, 1)
end = datetime(2012, 1, 1)
rng = pd.date_range(start, end)
rng
rng = pd.bdate_range(start, end)
rng
``date_range`` and ``bdate_range`` make it easy to generate a range of dates
using various combinations of parameters like ``start``, ``end``,
``periods``, and ``freq``:
.. ipython:: python
pd.date_range(start, end, freq='BM')
pd.date_range(start, end, freq='W')
pd.bdate_range(end=end, periods=20)
pd.bdate_range(start=start, periods=20)
The start and end dates are strictly inclusive. So it will not generate any
dates outside of those dates if specified.
.. _timeseries.timestamp-limits:
Timestamp limitations
---------------------
Since pandas represents timestamps in nanosecond resolution, the timespan that
can be represented using a 64-bit integer is limited to approximately 584 years:
.. ipython:: python
pd.Timestamp.min
pd.Timestamp.max
See :ref:`here <timeseries.oob>` for ways to represent data outside these bound.
.. _timeseries.datetimeindex:
DatetimeIndex
-------------
One of the main uses for ``DatetimeIndex`` is as an index for pandas objects.
The ``DatetimeIndex`` class contains many timeseries related optimizations:
- A large range of dates for various offsets are pre-computed and cached
under 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 is
very 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 has all the basic functionality of regular Index objects
and a smorgasbord of advanced timeseries-specific methods for easy frequency
processing.
.. seealso::
:ref:`Reindexing methods <basics.reindexing>`
.. note::
While pandas does not force you to have a sorted date index, some of these
methods may have unexpected or incorrect behavior if the dates are
unsorted. So please be careful.
``DatetimeIndex`` can be used like a regular index and offers all of its
intelligent functionality like selection, slicing, etc.
.. ipython:: python
rng = pd.date_range(start, end, freq='BM')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts.index
ts[:5].index
ts[::2].index
.. _timeseries.partialindexing:
DatetimeIndex Partial String Indexing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can pass in dates and strings that parse to dates as indexing parameters:
.. ipython:: python
ts['1/31/2011']
ts[datetime(2011, 12, 25):]
ts['10/31/2011':'12/31/2011']
To provide convenience for accessing longer time series, you can also pass in
the year or year and month as strings:
.. ipython:: python
ts['2011']
ts['2011-6']
This type of slicing will work on a DataFrame with a ``DateTimeIndex`` as well. Since the
partial string selection is a form of label slicing, the endpoints **will be** included. This
would include matching times on an included date. Here's an example:
.. ipython:: python
dft = pd.DataFrame(randn(100000,1),
columns=['A'],
index=pd.date_range('20130101',periods=100000,freq='T'))
dft
dft['2013']
This starts on the very first time in the month, and includes the last date & time for the month
.. ipython:: python
dft['2013-1':'2013-2']
This specifies a stop time **that includes all of the times on the last day**
.. ipython:: python
dft['2013-1':'2013-2-28']
This specifies an **exact** stop time (and is not the same as the above)
.. ipython:: python
dft['2013-1':'2013-2-28 00:00:00']
We are stopping on the included end-point as it is part of the index
.. ipython:: python
dft['2013-1-15':'2013-1-15 12:30:00']
.. warning::
The following selection will raise a ``KeyError``; otherwise this selection methodology
would be inconsistent with other selection methods in pandas (as this is not a *slice*, nor does it
resolve to one)
.. code-block:: python
dft['2013-1-15 12:30:00']
To select a single row, use ``.loc``
.. ipython:: python
dft.loc['2013-1-15 12:30:00']
.. versionadded:: 0.18.0
DatetimeIndex Partial String Indexing also works on DataFrames with a ``MultiIndex``. For example:
.. ipython:: python
dft2 = pd.DataFrame(np.random.randn(20, 1),
columns=['A'],
index=pd.MultiIndex.from_product([pd.date_range('20130101',
periods=10,
freq='12H'),
['a', 'b']]))
dft2
dft2.loc['2013-01-05']
idx = pd.IndexSlice
dft2 = dft2.swaplevel(0, 1).sort_index()
dft2.loc[idx[:, '2013-01-05'], :]
Datetime Indexing
~~~~~~~~~~~~~~~~~
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 frequency of the index. In contrast, indexing with datetime objects is exact, because the objects have exact meaning. These also follow the semantics of *including both endpoints*.
These ``datetime`` objects are specific ``hours, minutes,`` and ``seconds`` even though they were not explicitly specified (they are ``0``).
.. ipython:: python
dft[datetime(2013, 1, 1):datetime(2013,2,28)]
With no defaults.
.. ipython:: python
dft[datetime(2013, 1, 1, 10, 12, 0):datetime(2013, 2, 28, 10, 12, 0)]
Truncating & Fancy Indexing
~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``truncate`` convenience function is provided that is equivalent to slicing:
.. ipython:: python
ts.truncate(before='10/31/2011', after='12/31/2011')
Even complicated fancy indexing that breaks the DatetimeIndex's frequency
regularity will result in a ``DatetimeIndex`` (but frequency is lost):
.. ipython:: python
ts[[0, 2, 6]].index
.. _timeseries.offsets:
Time/Date Components
~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are several time/date properties that one can access from ``Timestamp`` or a collection of timestamps like a ``DateTimeIndex``.
.. csv-table::
:header: "Property", "Description"
:widths: 15, 65
year, "The year of the datetime"
month,"The month of the datetime"
day,"The days of the datetime"
hour,"The hour of the datetime"
minute,"The minutes of the datetime"
second,"The seconds of the datetime"
microsecond,"The microseconds of the datetime"
nanosecond,"The nanoseconds of the datetime"
date,"Returns datetime.date (does not contain timezone information)"
time,"Returns datetime.time (does not contain timezone information)"
dayofyear,"The ordinal day of year"
weekofyear,"The week ordinal of the year"
week,"The week ordinal of the year"
dayofweek,"The numer of the day of the week with Monday=0, Sunday=6"
weekday,"The number of the day of the week with Monday=0, Sunday=6"
weekday_name,"The name of the day in a week (ex: Friday)"
quarter,"Quarter of the date: Jan=Mar = 1, Apr-Jun = 2, etc."
days_in_month,"The number of days in the month of the datetime"
is_month_start,"Logical indicating if first day of month (defined by frequency)"
is_month_end,"Logical indicating if last day of month (defined by frequency)"
is_quarter_start,"Logical indicating if first day of quarter (defined by frequency)"
is_quarter_end,"Logical indicating if last day of quarter (defined by frequency)"
is_year_start,"Logical indicating if first day of year (defined by frequency)"
is_year_end,"Logical indicating if last day of year (defined by frequency)"
is_leap_year,"Logical indicating if the date belongs to a leap year"
Furthermore, if you have a ``Series`` with datetimelike values, then you can access these properties via the ``.dt`` accessor, see the :ref:`docs <basics.dt_accessors>`
DateOffset objects
------------------
In the preceding examples, we created DatetimeIndex objects at various
frequencies by passing in :ref:`frequency strings <timeseries.offset_aliases>`
like 'M', 'W', and 'BM to the ``freq`` keyword. Under the hood, these frequency
strings are being translated into an instance of pandas ``DateOffset``,
which represents a regular frequency increment. Specific offset logic like
"month", "business day", or "one hour" is represented in its various subclasses.
.. csv-table::
:header: "Class name", "Description"
:widths: 15, 65
DateOffset, "Generic offset class, defaults to 1 calendar day"
BDay, "business day (weekday)"
CDay, "custom business day (experimental)"
Week, "one week, optionally anchored on a day of the week"
WeekOfMonth, "the x-th day of the y-th week of each month"
LastWeekOfMonth, "the x-th day of the last week of each month"
MonthEnd, "calendar month end"
MonthBegin, "calendar month begin"
BMonthEnd, "business month end"
BMonthBegin, "business month begin"
CBMonthEnd, "custom business month end"
CBMonthBegin, "custom business month begin"
SemiMonthEnd, "15th (or other day_of_month) and calendar month end"
SemiMonthBegin, "15th (or other day_of_month) and calendar month begin"
QuarterEnd, "calendar quarter end"
QuarterBegin, "calendar quarter begin"
BQuarterEnd, "business quarter end"
BQuarterBegin, "business quarter begin"
FY5253Quarter, "retail (aka 52-53 week) quarter"
YearEnd, "calendar year end"
YearBegin, "calendar year begin"
BYearEnd, "business year end"
BYearBegin, "business year begin"
FY5253, "retail (aka 52-53 week) year"
BusinessHour, "business hour"
CustomBusinessHour, "custom business hour"
Hour, "one hour"
Minute, "one minute"
Second, "one second"
Milli, "one millisecond"
Micro, "one microsecond"
Nano, "one nanosecond"
The basic ``DateOffset`` takes the same arguments as
``dateutil.relativedelta``, which works like:
.. ipython:: python
d = datetime(2008, 8, 18, 9, 0)
d + relativedelta(months=4, days=5)
We could have done the same thing with ``DateOffset``:
.. ipython:: python
from pandas.tseries.offsets import *
d + DateOffset(months=4, days=5)
The key features of a ``DateOffset`` object are:
- it can be added / subtracted to/from a datetime object to obtain a
shifted date
- it can be multiplied by an integer (positive or negative) so that the
increment will be applied multiple times
- it has ``rollforward`` and ``rollback`` methods for moving a date forward
or backward to the next or previous "offset date"
Subclasses of ``DateOffset`` define the ``apply`` function which dictates
custom date increment logic, such as adding business days:
.. code-block:: python
class BDay(DateOffset):
"""DateOffset increments between business days"""
def apply(self, other):
...
.. ipython:: python
d - 5 * BDay()
d + BMonthEnd()
The ``rollforward`` and ``rollback`` methods do exactly what you would expect:
.. ipython:: python
d
offset = BMonthEnd()
offset.rollforward(d)
offset.rollback(d)
It's definitely worth exploring the ``pandas.tseries.offsets`` module and the
various docstrings for the classes.
These operations (``apply``, ``rollforward`` and ``rollback``) preserves time (hour, minute, etc) information by default. To reset time, use ``normalize=True`` keyword when creating the offset instance. If ``normalize=True``, result is normalized after the function is applied.
.. ipython:: python
day = Day()
day.apply(pd.Timestamp('2014-01-01 09:00'))
day = Day(normalize=True)
day.apply(pd.Timestamp('2014-01-01 09:00'))
hour = Hour()
hour.apply(pd.Timestamp('2014-01-01 22:00'))
hour = Hour(normalize=True)
hour.apply(pd.Timestamp('2014-01-01 22:00'))
hour.apply(pd.Timestamp('2014-01-01 23:00'))
Parametric offsets
~~~~~~~~~~~~~~~~~~
Some of the offsets can be "parameterized" when created to result in different
behaviors. For example, the ``Week`` offset for generating weekly data accepts a
``weekday`` parameter which results in the generated dates always lying on a
particular day of the week:
.. ipython:: python
d
d + Week()
d + Week(weekday=4)
(d + Week(weekday=4)).weekday()
d - Week()
``normalize`` option will be effective for addition and subtraction.
.. ipython:: python
d + Week(normalize=True)
d - Week(normalize=True)
Another example is parameterizing ``YearEnd`` with the specific ending month:
.. ipython:: python
d + YearEnd()
d + YearEnd(month=6)
.. _timeseries.offsetseries:
Using offsets with ``Series`` / ``DatetimeIndex``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offsets can be used with either a ``Series`` or ``DatetimeIndex`` to
apply the offset to each element.
.. ipython:: python
rng = pd.date_range('2012-01-01', '2012-01-03')
s = pd.Series(rng)
rng
rng + DateOffset(months=2)
s + DateOffset(months=2)
s - DateOffset(months=2)
If the offset class maps directly to a ``Timedelta`` (``Day``, ``Hour``,
``Minute``, ``Second``, ``Micro``, ``Milli``, ``Nano``) it can be
used exactly like a ``Timedelta`` - see the
:ref:`Timedelta section<timedeltas.operations>` for more examples.
.. ipython:: python
s - Day(2)
td = s - pd.Series(pd.date_range('2011-12-29', '2011-12-31'))
td
td + Minute(15)
Note that some offsets (such as ``BQuarterEnd``) do not have a
vectorized implementation. They can still be used but may
calculate significantly slower and will raise a ``PerformanceWarning``
.. ipython:: python
:okwarning:
rng + BQuarterEnd()
.. _timeseries.custombusinessdays:
Custom Business Days (Experimental)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``CDay`` or ``CustomBusinessDay`` class provides a parametric
``BusinessDay`` class which can be used to create customized business day
calendars 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.
.. ipython:: python
from pandas.tseries.offsets import CustomBusinessDay
weekmask_egypt = 'Sun Mon Tue Wed Thu'
# They also observe International Workers' Day so let's
# add that for a couple of years
holidays = ['2012-05-01', datetime(2013, 5, 1), np.datetime64('2014-05-01')]
bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt)
dt = datetime(2013, 4, 30)
dt + 2 * bday_egypt
Let's map to the weekday names
.. ipython:: python
dts = pd.date_range(dt, periods=5, freq=bday_egypt)
pd.Series(dts.weekday, dts).map(pd.Series('Mon Tue Wed Thu Fri Sat Sun'.split()))
As of v0.14 holiday calendars can be used to provide the list of holidays. See the
:ref:`holiday calendar<timeseries.holiday>` section for more information.
.. ipython:: python
from pandas.tseries.holiday import USFederalHolidayCalendar
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
# Friday before MLK Day
dt = datetime(2014, 1, 17)
# Tuesday after MLK Day (Monday is skipped because it's a holiday)
dt + bday_us
Monthly offsets that respect a certain holiday calendar can be defined
in the usual way.
.. ipython:: python
from pandas.tseries.offsets import CustomBusinessMonthBegin
bmth_us = CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())
# Skip new years
dt = datetime(2013, 12, 17)
dt + bmth_us
# Define date index with custom offset
pd.DatetimeIndex(start='20100101',end='20120101',freq=bmth_us)
.. note::
The frequency string 'C' is used to indicate that a CustomBusinessDay
DateOffset is used, it is important to note that since CustomBusinessDay is
a parameterised type, instances of CustomBusinessDay may differ and this is
not detectable from the 'C' frequency string. The user therefore needs to
ensure that the 'C' frequency string is used consistently within the user's
application.
.. _timeseries.businesshour:
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.
If target ``Timestamp`` is out of business hours, move to the next business hour then increment it.
If the result exceeds the business hours end, remaining is added to the next business day.
.. ipython:: python
bh = BusinessHour()
bh
# 2014-08-01 is Friday
pd.Timestamp('2014-08-01 10:00').weekday()
pd.Timestamp('2014-08-01 10:00') + bh
# Below example is the same as: pd.Timestamp('2014-08-01 09:00') + bh
pd.Timestamp('2014-08-01 08:00') + bh
# If the results is on the end time, move to the next business day
pd.Timestamp('2014-08-01 16:00') + bh
# Remainings are added to the next day
pd.Timestamp('2014-08-01 16:30') + bh
# Adding 2 business hours
pd.Timestamp('2014-08-01 10:00') + BusinessHour(2)
# Subtracting 3 business hours
pd.Timestamp('2014-08-01 10:00') + BusinessHour(-3)
Also, you can specify ``start`` and ``end`` time by keywords.
Argument must be ``str`` which has ``hour:minute`` representation or ``datetime.time`` instance.
Specifying seconds, microseconds and nanoseconds as business hour results in ``ValueError``.
.. ipython:: python
bh = BusinessHour(start='11:00', end=time(20, 0))
bh
pd.Timestamp('2014-08-01 13:00') + bh
pd.Timestamp('2014-08-01 09:00') + bh
pd.Timestamp('2014-08-01 18:00') + bh
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``.
.. ipython:: python
bh = BusinessHour(start='17:00', end='09:00')
bh
pd.Timestamp('2014-08-01 17:00') + bh
pd.Timestamp('2014-08-01 23:00') + bh
# Although 2014-08-02 is Satuaday,
# it is valid because it starts from 08-01 (Friday).
pd.Timestamp('2014-08-02 04:00') + bh
# Although 2014-08-04 is Monday,
# it is out of business hours because it starts from 08-03 (Sunday).
pd.Timestamp('2014-08-04 04:00') + bh
Applying ``BusinessHour.rollforward`` and ``rollback`` to out of business hours results in
the next business hour start or previous day's end. Different from other offsets, ``BusinessHour.rollforward``
may 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`` and
``2014-08-04 09:00``.
.. ipython:: python
# This adjusts a Timestamp to business hour edge
BusinessHour().rollback(pd.Timestamp('2014-08-02 15:00'))
BusinessHour().rollforward(pd.Timestamp('2014-08-02 15:00'))
# It is the same as BusinessHour().apply(pd.Timestamp('2014-08-01 17:00')).
# And it is the same as BusinessHour().apply(pd.Timestamp('2014-08-04 09:00'))
BusinessHour().apply(pd.Timestamp('2014-08-02 15:00'))
# BusinessDay results (for reference)
BusinessHour().rollforward(pd.Timestamp('2014-08-02'))
# It is the same as BusinessDay().apply(pd.Timestamp('2014-08-01'))
# The result is the same as rollworward because BusinessDay never overlap.
BusinessHour().apply(pd.Timestamp('2014-08-02'))
``BusinessHour`` regards Saturday and Sunday as holidays. To use arbitrary holidays,
you can use ``CustomBusinessHour`` offset, see :ref:`Custom Business Hour <timeseries.custombusinesshour>`:
.. _timeseries.custombusinesshour:
Custom Business Hour
~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.18.1
The ``CustomBusinessHour`` is a mixture of ``BusinessHour`` and ``CustomBusinessDay`` which
allows you to specify arbitrary holidays. ``CustomBusinessHour`` works as the same
as ``BusinessHour`` except that it skips specified custom holidays.
.. ipython:: python
from pandas.tseries.holiday import USFederalHolidayCalendar
bhour_us = CustomBusinessHour(calendar=USFederalHolidayCalendar())
# Friday before MLK Day
dt = datetime(2014, 1, 17, 15)
dt + bhour_us
# Tuesday after MLK Day (Monday is skipped because it's a holiday)
dt + bhour_us * 2
You can use keyword arguments suported by either ``BusinessHour`` and ``CustomBusinessDay``.
.. ipython:: python
bhour_mon = CustomBusinessHour(start='10:00', weekmask='Tue Wed Thu Fri')
# Monday is skipped because it's a holiday, business hour starts from 10:00
dt + bhour_mon * 2
.. _timeseries.offset_aliases:
Offset Aliases
~~~~~~~~~~~~~~
A number of string aliases are given to useful common time series
frequencies. We will refer to these aliases as *offset aliases*
(referred to as *time rules* prior to v0.8.0).
.. csv-table::
:header: "Alias", "Description"
:widths: 15, 100
"B", "business day frequency"
"C", "custom business day frequency (experimental)"
"D", "calendar day frequency"
"W", "weekly frequency"
"M", "month end frequency"
"SM", "semi-month end frequency (15th and end of month)"
"BM", "business month end frequency"
"CBM", "custom business month end frequency"
"MS", "month start frequency"
"SMS", "semi-month start frequency (1st and 15th)"
"BMS", "business month start frequency"
"CBMS", "custom business month start frequency"
"Q", "quarter end frequency"
"BQ", "business quarter endfrequency"
"QS", "quarter start frequency"
"BQS", "business quarter start frequency"
"A", "year end frequency"
"BA", "business year end frequency"
"AS", "year start frequency"
"BAS", "business year start frequency"
"BH", "business hour frequency"
"H", "hourly frequency"
"T, min", "minutely frequency"
"S", "secondly frequency"
"L, ms", "milliseconds"
"U, us", "microseconds"
"N", "nanoseconds"
Combining Aliases
~~~~~~~~~~~~~~~~~