/
dates.py
1926 lines (1550 loc) · 66 KB
/
dates.py
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
"""
Matplotlib provides sophisticated date plotting capabilities, standing on the
shoulders of python :mod:`datetime` and the add-on module :mod:`dateutil`.
By default, Matplotlib uses the units machinery described in
`~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64`
objects when plotted on an x- or y-axis. The user does not
need to do anything for dates to be formatted, but dates often have strict
formatting needs, so this module provides many axis locators and formatters.
A basic example using `numpy.datetime64` is::
import numpy as np
times = np.arange(np.datetime64('2001-01-02'),
np.datetime64('2002-02-03'), np.timedelta64(75, 'm'))
y = np.random.randn(len(times))
fig, ax = plt.subplots()
ax.plot(times, y)
.. seealso::
- :doc:`/gallery/text_labels_and_annotations/date`
- :doc:`/gallery/ticks/date_concise_formatter`
- :doc:`/gallery/ticks/date_demo_convert`
.. _date-format:
Matplotlib date format
----------------------
Matplotlib represents dates using floating point numbers specifying the number
of days since a default epoch of 1970-01-01 UTC; for example,
1970-01-01, 06:00 is the floating point number 0.25. The formatters and
locators require the use of `datetime.datetime` objects, so only dates between
year 0001 and 9999 can be represented. Microsecond precision
is achievable for (approximately) 70 years on either side of the epoch, and
20 microseconds for the rest of the allowable range of dates (year 0001 to
9999). The epoch can be changed at import time via `.dates.set_epoch` or
:rc:`dates.epoch` to other dates if necessary; see
:doc:`/gallery/ticks/date_precision_and_epochs` for a discussion.
.. note::
Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern
microsecond precision and also made the default axis limit of 0 an invalid
datetime. In 3.3 the epoch was changed as above. To convert old
ordinal floats to the new epoch, users can do::
new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
There are a number of helper functions to convert between :mod:`datetime`
objects and Matplotlib dates:
.. currentmodule:: matplotlib.dates
.. autosummary::
:nosignatures:
datestr2num
date2num
num2date
num2timedelta
drange
set_epoch
get_epoch
.. note::
Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar
for all conversions between dates and floating point numbers. This practice
is not universal, and calendar differences can cause confusing
differences between what Python and Matplotlib give as the number of days
since 0001-01-01 and what other software and databases yield. For
example, the US Naval Observatory uses a calendar that switches
from Julian to Gregorian in October, 1582. Hence, using their
calculator, the number of days between 0001-01-01 and 2006-04-01 is
732403, whereas using the Gregorian calendar via the datetime
module we find::
In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
Out[1]: 732401
All the Matplotlib date converters, tickers and formatters are timezone aware.
If no explicit timezone is provided, :rc:`timezone` is assumed. If you want to
use a custom time zone, pass a `datetime.tzinfo` instance with the tz keyword
argument to `num2date`, `.Axis.axis_date`, and any custom date tickers or
locators you create.
A wide range of specific and general purpose date tick locators and
formatters are provided in this module. See
:mod:`matplotlib.ticker` for general information on tick locators
and formatters. These are described below.
The dateutil_ module provides additional code to handle date ticking, making it
easy to place ticks on any kinds of dates. See examples below.
.. _dateutil: https://dateutil.readthedocs.io
Date tickers
------------
Most of the date tickers can locate single or multiple values. For example::
# import constants for the days of the week
from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU
# tick on mondays every week
loc = WeekdayLocator(byweekday=MO, tz=tz)
# tick on mondays and saturdays
loc = WeekdayLocator(byweekday=(MO, SA))
In addition, most of the constructors take an interval argument::
# tick on mondays every second week
loc = WeekdayLocator(byweekday=MO, interval=2)
The rrule locator allows completely general date ticking::
# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
The available date tickers are:
* `MicrosecondLocator`: Locate microseconds.
* `SecondLocator`: Locate seconds.
* `MinuteLocator`: Locate minutes.
* `HourLocator`: Locate hours.
* `DayLocator`: Locate specified days of the month.
* `WeekdayLocator`: Locate days of the week, e.g., MO, TU.
* `MonthLocator`: Locate months, e.g., 7 for July.
* `YearLocator`: Locate years that are multiples of base.
* `RRuleLocator`: Locate using a `matplotlib.dates.rrulewrapper`.
`.rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule` which
allow almost arbitrary date tick specifications. See :doc:`rrule example
</gallery/ticks/date_demo_rrule>`.
* `AutoDateLocator`: On autoscale, this class picks the best `DateLocator`
(e.g., `RRuleLocator`) to set the view limits and the tick locations. If
called with ``interval_multiples=True`` it will make ticks line up with
sensible multiples of the tick intervals. E.g. if the interval is 4 hours,
it will pick hours 0, 4, 8, etc as ticks. This behaviour is not guaranteed
by default.
Date formatters
---------------
The available date formatters are:
* `AutoDateFormatter`: attempts to figure out the best format to use. This is
most useful when used with the `AutoDateLocator`.
* `ConciseDateFormatter`: also attempts to figure out the best format to use,
and to make the format as compact as possible while still having complete
date information. This is most useful when used with the `AutoDateLocator`.
* `DateFormatter`: use `~datetime.datetime.strftime` format strings.
"""
import datetime
import functools
import logging
import math
import re
from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
SECONDLY)
from dateutil.relativedelta import relativedelta
import dateutil.parser
import dateutil.tz
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, ticker, units
__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
'epoch2num', 'num2epoch', 'set_epoch', 'get_epoch', 'DateFormatter',
'ConciseDateFormatter', 'AutoDateFormatter',
'DateLocator', 'RRuleLocator', 'AutoDateLocator', 'YearLocator',
'MonthLocator', 'WeekdayLocator',
'DayLocator', 'HourLocator', 'MinuteLocator',
'SecondLocator', 'MicrosecondLocator',
'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
'DateConverter', 'ConciseDateConverter')
_log = logging.getLogger(__name__)
UTC = datetime.timezone.utc
def _get_rc_timezone():
"""Retrieve the preferred timezone from the rcParams dictionary."""
s = mpl.rcParams['timezone']
if s == 'UTC':
return UTC
return dateutil.tz.gettz(s)
"""
Time-related constants.
"""
EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
# EPOCH_OFFSET is not used by matplotlib
JULIAN_OFFSET = 1721424.5 # Julian date at 0000-12-31
# note that the Julian day epoch is achievable w/
# np.datetime64('-4713-11-24T12:00:00'); datetime64 is proleptic
# Gregorian and BC has a one-year offset. So
# np.datetime64('0000-12-31') - np.datetime64('-4713-11-24T12:00') = 1721424.5
# Ref: https://en.wikipedia.org/wiki/Julian_day
MICROSECONDLY = SECONDLY + 1
HOURS_PER_DAY = 24.
MIN_PER_HOUR = 60.
SEC_PER_MIN = 60.
MONTHS_PER_YEAR = 12.
DAYS_PER_WEEK = 7.
DAYS_PER_MONTH = 30.
DAYS_PER_YEAR = 365.0
MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
MO, TU, WE, TH, FR, SA, SU)
WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
# default epoch: passed to np.datetime64...
_epoch = None
def _reset_epoch_test_example():
"""
Reset the Matplotlib date epoch so it can be set again.
Only for use in tests and examples.
"""
global _epoch
_epoch = None
def set_epoch(epoch):
"""
Set the epoch (origin for dates) for datetime calculations.
The default epoch is :rc:`dates.epoch` (by default 1970-01-01T00:00).
If microsecond accuracy is desired, the date being plotted needs to be
within approximately 70 years of the epoch. Matplotlib internally
represents dates as days since the epoch, so floating point dynamic
range needs to be within a factor of 2^52.
`~.dates.set_epoch` must be called before any dates are converted
(i.e. near the import section) or a RuntimeError will be raised.
See also :doc:`/gallery/ticks/date_precision_and_epochs`.
Parameters
----------
epoch : str
valid UTC date parsable by `numpy.datetime64` (do not include
timezone).
"""
global _epoch
if _epoch is not None:
raise RuntimeError('set_epoch must be called before dates plotted.')
_epoch = epoch
def get_epoch():
"""
Get the epoch used by `.dates`.
Returns
-------
epoch : str
String for the epoch (parsable by `numpy.datetime64`).
"""
global _epoch
if _epoch is None:
_epoch = mpl.rcParams['date.epoch']
return _epoch
def _dt64_to_ordinalf(d):
"""
Convert `numpy.datetime64` or an ndarray of those types to Gregorian
date as UTC float relative to the epoch (see `.get_epoch`). Roundoff
is float64 precision. Practically: microseconds for dates between
290301 BC, 294241 AD, milliseconds for larger dates
(see `numpy.datetime64`).
"""
# the "extra" ensures that we at least allow the dynamic range out to
# seconds. That should get out to +/-2e11 years.
dseconds = d.astype('datetime64[s]')
extra = (d - dseconds).astype('timedelta64[ns]')
t0 = np.datetime64(get_epoch(), 's')
dt = (dseconds - t0).astype(np.float64)
dt += extra.astype(np.float64) / 1.0e9
dt = dt / SEC_PER_DAY
NaT_int = np.datetime64('NaT').astype(np.int64)
d_int = d.astype(np.int64)
try:
dt[d_int == NaT_int] = np.nan
except TypeError:
if d_int == NaT_int:
dt = np.nan
return dt
def _from_ordinalf(x, tz=None):
"""
Convert Gregorian float of the date, preserving hours, minutes,
seconds and microseconds. Return value is a `.datetime`.
The input date *x* is a float in ordinal days at UTC, and the output will
be the specified `.datetime` object corresponding to that time in
timezone *tz*, or if *tz* is ``None``, in the timezone specified in
:rc:`timezone`.
"""
if tz is None:
tz = _get_rc_timezone()
dt = (np.datetime64(get_epoch()) +
np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'):
raise ValueError(f'Date ordinal {x} converts to {dt} (using '
f'epoch {get_epoch()}), but Matplotlib dates must be '
'between year 0001 and 9999.')
# convert from datetime64 to datetime:
dt = dt.tolist()
# datetime64 is always UTC:
dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC'))
# but maybe we are working in a different timezone so move.
dt = dt.astimezone(tz)
# fix round off errors
if np.abs(x) > 70 * 365:
# if x is big, round off to nearest twenty microseconds.
# This avoids floating point roundoff error
ms = round(dt.microsecond / 20) * 20
if ms == 1000000:
dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
else:
dt = dt.replace(microsecond=ms)
return dt
# a version of _from_ordinalf that can operate on numpy arrays
_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O")
# a version of dateutil.parser.parse that can operate on numpy arrays
_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
def datestr2num(d, default=None):
"""
Convert a date string to a datenum using `dateutil.parser.parse`.
Parameters
----------
d : str or sequence of str
The dates to convert.
default : datetime.datetime, optional
The default date to use when fields are missing in *d*.
"""
if isinstance(d, str):
dt = dateutil.parser.parse(d, default=default)
return date2num(dt)
else:
if default is not None:
d = [dateutil.parser.parse(s, default=default) for s in d]
d = np.asarray(d)
if not d.size:
return d
return date2num(_dateutil_parser_parse_np_vectorized(d))
def date2num(d):
"""
Convert datetime objects to Matplotlib dates.
Parameters
----------
d : `datetime.datetime` or `numpy.datetime64` or sequences of these
Returns
-------
float or sequence of floats
Number of days since the epoch. See `.get_epoch` for the
epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If
the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
("1970-01-01T12:00:00") returns 0.5.
Notes
-----
The Gregorian calendar is assumed; this is not universal practice.
For details see the module docstring.
"""
if hasattr(d, "values"):
# this unpacks pandas series or dataframes...
d = d.values
# make an iterable, but save state to unpack later:
iterable = np.iterable(d)
if not iterable:
d = [d]
d = np.asarray(d)
# convert to datetime64 arrays, if not already:
if not np.issubdtype(d.dtype, np.datetime64):
# datetime arrays
if not d.size:
# deals with an empty array...
return d
tzi = getattr(d[0], 'tzinfo', None)
if tzi is not None:
# make datetime naive:
d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
d = np.asarray(d)
d = d.astype('datetime64[us]')
d = _dt64_to_ordinalf(d)
return d if iterable else d[0]
def julian2num(j):
"""
Convert a Julian date (or sequence) to a Matplotlib date (or sequence).
Parameters
----------
j : float or sequence of floats
Julian dates (days relative to 4713 BC Jan 1, 12:00:00 Julian
calendar or 4714 BC Nov 24, 12:00:00, proleptic Gregorian calendar).
Returns
-------
float or sequence of floats
Matplotlib dates (days relative to `.get_epoch`).
"""
ep = np.datetime64(get_epoch(), 'h').astype(float) / 24.
ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.
# Julian offset defined above is relative to 0000-12-31, but we need
# relative to our current epoch:
dt = JULIAN_OFFSET - ep0 + ep
return np.subtract(j, dt) # Handles both scalar & nonscalar j.
def num2julian(n):
"""
Convert a Matplotlib date (or sequence) to a Julian date (or sequence).
Parameters
----------
n : float or sequence of floats
Matplotlib dates (days relative to `.get_epoch`).
Returns
-------
float or sequence of floats
Julian dates (days relative to 4713 BC Jan 1, 12:00:00).
"""
ep = np.datetime64(get_epoch(), 'h').astype(float) / 24.
ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.
# Julian offset defined above is relative to 0000-12-31, but we need
# relative to our current epoch:
dt = JULIAN_OFFSET - ep0 + ep
return np.add(n, dt) # Handles both scalar & nonscalar j.
def num2date(x, tz=None):
"""
Convert Matplotlib dates to `~datetime.datetime` objects.
Parameters
----------
x : float or sequence of floats
Number of days (fraction part represents hours, minutes, seconds)
since the epoch. See `.get_epoch` for the
epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`.
tz : str, default: :rc:`timezone`
Timezone of *x*.
Returns
-------
`~datetime.datetime` or sequence of `~datetime.datetime`
Dates are returned in timezone *tz*.
If *x* is a sequence, a sequence of `~datetime.datetime` objects will
be returned.
Notes
-----
The addition of one here is a historical artifact. Also, note that the
Gregorian calendar is assumed; this is not universal practice.
For details, see the module docstring.
"""
if tz is None:
tz = _get_rc_timezone()
return _from_ordinalf_np_vectorized(x, tz).tolist()
_ordinalf_to_timedelta_np_vectorized = np.vectorize(
lambda x: datetime.timedelta(days=x), otypes="O")
def num2timedelta(x):
"""
Convert number of days to a `~datetime.timedelta` object.
If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
be returned.
Parameters
----------
x : float, sequence of floats
Number of days. The fraction part represents hours, minutes, seconds.
Returns
-------
`datetime.timedelta` or list[`datetime.timedelta`]
"""
return _ordinalf_to_timedelta_np_vectorized(x).tolist()
def drange(dstart, dend, delta):
"""
Return a sequence of equally spaced Matplotlib dates.
The dates start at *dstart* and reach up to, but not including *dend*.
They are spaced by *delta*.
Parameters
----------
dstart, dend : `~datetime.datetime`
The date limits.
delta : `datetime.timedelta`
Spacing of the dates.
Returns
-------
`numpy.array`
A list floats representing Matplotlib dates.
"""
f1 = date2num(dstart)
f2 = date2num(dend)
step = delta.total_seconds() / SEC_PER_DAY
# calculate the difference between dend and dstart in times of delta
num = int(np.ceil((f2 - f1) / step))
# calculate end of the interval which will be generated
dinterval_end = dstart + num * delta
# ensure, that an half open interval will be generated [dstart, dend)
if dinterval_end >= dend:
# if the endpoint is greater than dend, just subtract one delta
dinterval_end -= delta
num -= 1
f2 = date2num(dinterval_end) # new float-endpoint
return np.linspace(f1, f2, num + 1)
def _wrap_in_tex(text):
p = r'([a-zA-Z]+)'
ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
# Braces ensure symbols are not spaced like binary operators.
ret_text = ret_text.replace('-', '{-}').replace(':', '{:}')
# To not concatenate space between numbers.
ret_text = ret_text.replace(' ', r'\;')
ret_text = '$\\mathdefault{' + ret_text + '}$'
ret_text = ret_text.replace('$\\mathdefault{}$', '')
return ret_text
## date tickers and formatters ###
class DateFormatter(ticker.Formatter):
"""
Format a tick (in days since the epoch) with a
`~datetime.datetime.strftime` format string.
"""
def __init__(self, fmt, tz=None, *, usetex=None):
"""
Parameters
----------
fmt : str
`~datetime.datetime.strftime` format string
tz : `datetime.tzinfo`, default: :rc:`timezone`
Ticks timezone.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the
results of the formatter.
"""
if tz is None:
tz = _get_rc_timezone()
self.fmt = fmt
self.tz = tz
self._usetex = (usetex if usetex is not None else
mpl.rcParams['text.usetex'])
def __call__(self, x, pos=0):
result = num2date(x, self.tz).strftime(self.fmt)
return _wrap_in_tex(result) if self._usetex else result
def set_tzinfo(self, tz):
self.tz = tz
class ConciseDateFormatter(ticker.Formatter):
"""
A `.Formatter` which attempts to figure out the best format to use for the
date, and to make it as compact as possible, but still be complete. This is
most useful when used with the `AutoDateLocator`::
>>> locator = AutoDateLocator()
>>> formatter = ConciseDateFormatter(locator)
Parameters
----------
locator : `.ticker.Locator`
Locator that this axis is using.
tz : str, optional
Passed to `.dates.date2num`.
formats : list of 6 strings, optional
Format strings for 6 levels of tick labelling: mostly years,
months, days, hours, minutes, and seconds. Strings use
the same format codes as `~datetime.datetime.strftime`. Default is
``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
zero_formats : list of 6 strings, optional
Format strings for tick labels that are "zeros" for a given tick
level. For instance, if most ticks are months, ticks around 1 Jan 2005
will be labeled "Dec", "2005", "Feb". The default is
``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
offset_formats : list of 6 strings, optional
Format strings for the 6 levels that is applied to the "offset"
string found on the right side of an x-axis, or top of a y-axis.
Combined with the tick labels this should completely specify the
date. The default is::
['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
show_offset : bool, default: True
Whether to show the offset or not.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the results
of the formatter.
Examples
--------
See :doc:`/gallery/ticks/date_concise_formatter`
.. plot::
import datetime
import matplotlib.dates as mdates
base = datetime.datetime(2005, 2, 1)
dates = np.array([base + datetime.timedelta(hours=(2 * i))
for i in range(732)])
N = len(dates)
np.random.seed(19680801)
y = np.cumsum(np.random.randn(N))
fig, ax = plt.subplots(constrained_layout=True)
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(dates, y)
ax.set_title('Concise Date Formatter')
"""
def __init__(self, locator, tz=None, formats=None, offset_formats=None,
zero_formats=None, show_offset=True, *, usetex=None):
"""
Autoformat the date labels. The default format is used to form an
initial string, and then redundant elements are removed.
"""
self._locator = locator
self._tz = tz
self.defaultfmt = '%Y'
# there are 6 levels with each level getting a specific format
# 0: mostly years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds
if formats:
if len(formats) != 6:
raise ValueError('formats argument must be a list of '
'6 format strings (or None)')
self.formats = formats
else:
self.formats = ['%Y', # ticks are mostly years
'%b', # ticks are mostly months
'%d', # ticks are mostly days
'%H:%M', # hrs
'%H:%M', # min
'%S.%f', # secs
]
# fmt for zeros ticks at this level. These are
# ticks that should be labeled w/ info the level above.
# like 1 Jan can just be labelled "Jan". 02:02:00 can
# just be labeled 02:02.
if zero_formats:
if len(zero_formats) != 6:
raise ValueError('zero_formats argument must be a list of '
'6 format strings (or None)')
self.zero_formats = zero_formats
elif formats:
# use the users formats for the zero tick formats
self.zero_formats = [''] + self.formats[:-1]
else:
# make the defaults a bit nicer:
self.zero_formats = [''] + self.formats[:-1]
self.zero_formats[3] = '%b-%d'
if offset_formats:
if len(offset_formats) != 6:
raise ValueError('offsetfmts argument must be a list of '
'6 format strings (or None)')
self.offset_formats = offset_formats
else:
self.offset_formats = ['',
'%Y',
'%Y-%b',
'%Y-%b-%d',
'%Y-%b-%d',
'%Y-%b-%d %H:%M']
self.offset_string = ''
self.show_offset = show_offset
self._usetex = (usetex if usetex is not None else
mpl.rcParams['text.usetex'])
def __call__(self, x, pos=None):
formatter = DateFormatter(self.defaultfmt, self._tz,
usetex=self._usetex)
return formatter(x, pos=pos)
def format_ticks(self, values):
tickdatetime = [num2date(value, tz=self._tz) for value in values]
tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
# basic algorithm:
# 1) only display a part of the date if it changes over the ticks.
# 2) don't display the smaller part of the date if:
# it is always the same or if it is the start of the
# year, month, day etc.
# fmt for most ticks at this level
fmts = self.formats
# format beginnings of days, months, years, etc.
zerofmts = self.zero_formats
# offset fmt are for the offset in the upper left of the
# or lower right of the axis.
offsetfmts = self.offset_formats
show_offset = self.show_offset
# determine the level we will label at:
# mostly 0: years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds, 6: microseconds
for level in range(5, -1, -1):
if len(np.unique(tickdate[:, level])) > 1:
if level < 2:
show_offset = False
break
elif level == 0:
# all tickdate are the same, so only micros might be different
# set to the most precise (6: microseconds doesn't exist...)
level = 5
# level is the basic level we will label at.
# now loop through and decide the actual ticklabels
zerovals = [0, 1, 1, 0, 0, 0, 0]
labels = [''] * len(tickdate)
for nn in range(len(tickdate)):
if level < 5:
if tickdate[nn][level] == zerovals[level]:
fmt = zerofmts[level]
else:
fmt = fmts[level]
else:
# special handling for seconds + microseconds
if (tickdatetime[nn].second == tickdatetime[nn].microsecond
== 0):
fmt = zerofmts[level]
else:
fmt = fmts[level]
labels[nn] = tickdatetime[nn].strftime(fmt)
# special handling of seconds and microseconds:
# strip extra zeros and decimal if possible.
# this is complicated by two factors. 1) we have some level-4 strings
# here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
# same number of decimals for each string (i.e. 0.5 and 1.0).
if level >= 5:
trailing_zeros = min(
(len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
default=None)
if trailing_zeros:
for nn in range(len(labels)):
if '.' in labels[nn]:
labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
if show_offset:
# set the offset string:
self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
if self._usetex:
self.offset_string = _wrap_in_tex(self.offset_string)
else:
self.offset_string = ''
if self._usetex:
return [_wrap_in_tex(l) for l in labels]
else:
return labels
def get_offset(self):
return self.offset_string
def format_data_short(self, value):
return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
class AutoDateFormatter(ticker.Formatter):
"""
A `.Formatter` which attempts to figure out the best format to use. This
is most useful when used with the `AutoDateLocator`.
`.AutoDateFormatter` has a ``.scale`` dictionary that maps tick scales (the
interval in days between one major tick) to format strings; this dictionary
defaults to ::
self.scaled = {
DAYS_PER_YEAR: rcParams['date.autoformat.year'],
DAYS_PER_MONTH: rcParams['date.autoformat.month'],
1: rcParams['date.autoformat.day'],
1 / HOURS_PER_DAY: rcParams['date.autoformat.hour'],
1 / MINUTES_PER_DAY: rcParams['date.autoformat.minute'],
1 / SEC_PER_DAY: rcParams['date.autoformat.second'],
1 / MUSECONDS_PER_DAY: rcParams['date.autoformat.microsecond'],
}
The formatter uses the format string corresponding to the lowest key in
the dictionary that is greater or equal to the current scale. Dictionary
entries can be customized::
locator = AutoDateLocator()
formatter = AutoDateFormatter(locator)
formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec
Custom callables can also be used instead of format strings. The following
example shows how to use a custom format function to strip trailing zeros
from decimal seconds and adds the date to the first ticklabel::
def my_format_function(x, pos=None):
x = matplotlib.dates.num2date(x)
if pos == 0:
fmt = '%D %H:%M:%S.%f'
else:
fmt = '%H:%M:%S.%f'
label = x.strftime(fmt)
label = label.rstrip("0")
label = label.rstrip(".")
return label
formatter.scaled[1/(24*60)] = my_format_function
"""
# This can be improved by providing some user-level direction on
# how to choose the best format (precedence, etc.).
# Perhaps a 'struct' that has a field for each time-type where a
# zero would indicate "don't show" and a number would indicate
# "show" with some sort of priority. Same priorities could mean
# show all with the same priority.
# Or more simply, perhaps just a format string for each
# possibility...
def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *,
usetex=None):
"""
Autoformat the date labels.
Parameters
----------
locator : `.ticker.Locator`
Locator that this axis is using.
tz : str, optional
Passed to `.dates.date2num`.
defaultfmt : str
The default format to use if none of the values in ``self.scaled``
are greater than the unit returned by ``locator._get_unit()``.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the
results of the formatter. If any entries in ``self.scaled`` are set
as functions, then it is up to the customized function to enable or
disable TeX's math mode itself.
"""
self._locator = locator
self._tz = tz
self.defaultfmt = defaultfmt
self._formatter = DateFormatter(self.defaultfmt, tz)
rcParams = mpl.rcParams
self._usetex = (usetex if usetex is not None else
mpl.rcParams['text.usetex'])
self.scaled = {
DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
1: rcParams['date.autoformatter.day'],
1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']
}
def _set_locator(self, locator):
self._locator = locator
def __call__(self, x, pos=None):
try:
locator_unit_scale = float(self._locator._get_unit())
except AttributeError:
locator_unit_scale = 1
# Pick the first scale which is greater than the locator unit.
fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
if scale >= locator_unit_scale),
self.defaultfmt)
if isinstance(fmt, str):
self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex)
result = self._formatter(x, pos)
elif callable(fmt):
result = fmt(x, pos)
else:
raise TypeError('Unexpected type passed to {0!r}.'.format(self))
return result
class rrulewrapper:
def __init__(self, freq, tzinfo=None, **kwargs):
kwargs['freq'] = freq
self._base_tzinfo = tzinfo
self._update_rrule(**kwargs)
def set(self, **kwargs):
self._construct.update(kwargs)
self._update_rrule(**self._construct)
def _update_rrule(self, **kwargs):
tzinfo = self._base_tzinfo
# rrule does not play nicely with time zones - especially pytz time
# zones, it's best to use naive zones and attach timezones once the
# datetimes are returned
if 'dtstart' in kwargs: