

matplotlib.dates¶Matplotlib provides sophisticated date plotting capabilities, standing on theshoulders of pythondatetime, the add-on modulespytz anddateutil.datetime objects are converted to floating pointnumbers which represent time in days since 0001-01-01 UTC, plus 1. Forexample, 0001-01-01, 06:00 is 1.25, not 0.25. The helper functionsdate2num(),num2date() anddrange() are used to facilitateeasy conversion to and fromdatetime and numeric ranges.
Note
Like Python’s datetime, mpl uses the Gregorian calendar for allconversions between dates and floating point numbers. This practiceis not universal, and calendar differences can cause confusingdifferences between what Python and mpl give as the number of dayssince 0001-01-01 and what other software and databases yield. Forexample, the US Naval Observatory uses a calendar that switchesfrom Julian to Gregorian in October, 1582. Hence, using theircalculator, the number of days between 0001-01-01 and 2006-04-01 is732403, whereas using the Gregorian calendar via the datetimemodule we find:
In[31]:date(2006,4,1).toordinal()-date(1,1,1).toordinal()Out[31]:732401
A wide range of specific and general purpose date tick locators andformatters are provided in this module. Seematplotlib.ticker for general information on tick locatorsand formatters. These are described below.
All the matplotlib date converters, tickers and formatters aretimezone aware, and the default timezone is given by the timezoneparameter in yourmatplotlibrc file. If you leave out atz timezone instance, the default from your rc file will beassumed. If you want to use a custom time zone, pass apytz.timezone instance with the tz keyword argument tonum2date(),plot_date(), and any custom date tickers orlocators you create. Seepytz forinformation onpytz and timezone handling.
Thedateutil module providesadditional code to handle date ticking, making it easy to place tickson any kinds of dates. See examples below.
Most of the date tickers can locate single or multiple values. Forexample:
# import constants for the days of the weekfrommatplotlib.datesimportMO,TU,WE,TH,FR,SA,SU# tick on mondays every weekloc=WeekdayLocator(byweekday=MO,tz=tz)# tick on mondays and saturdaysloc=WeekdayLocator(byweekday=(MO,SA))
In addition, most of the constructors take an interval argument:
# tick on mondays every second weekloc=WeekdayLocator(byweekday=MO,interval=2)
The rrule locator allows completely general date ticking:
# tick every 5th easterrule=rrulewrapper(YEARLY,byeaster=1,interval=5)loc=RRuleLocator(rule)
Here are all the date tickers:
MinuteLocator: locate minutesHourLocator: locate hoursDayLocator: locate specifed days of the monthWeekdayLocator: Locate days of the week, e.g., MO, TUMonthLocator: locate months, e.g., 7 for julyYearLocator: locate years that are multiples of baseRRuleLocator: locate using amatplotlib.dates.rrulewrapper. Therrulewrapperis a simple wrapper around adateutil.rrule(dateutil) which allow almostarbitrary date tick specifications. Seerrule example.AutoDateLocator: On autoscale, this class picks the bestMultipleDateLocatorto set the view limits and the ticklocations.
Here all all the date formatters:
AutoDateFormatter: attempts to figure out the best formatto use. This is most useful when used with theAutoDateLocator.DateFormatter: usestrftime()format stringsIndexDateFormatter: date plots with implicitxindexing.
matplotlib.dates.date2num(d)¶d is either adatetime instance or a sequence of datetimes.
Return value is a floating point number (or sequence of floats)which gives the number of days (fraction part represents hours,minutes, seconds) since 0001-01-01 00:00:00 UTC,plusone.The addition of one here is a historical artifact. Also, notethat the Gregorian calendar is assumed; this is not universalpractice. For details, see the module docstring.
matplotlib.dates.num2date(x,tz=None)¶x is a float value which gives the number of days(fraction part represents hours, minutes, seconds) since0001-01-01 00:00:00 UTCplusone.The addition of one here is a historical artifact. Also, notethat the Gregorian calendar is assumed; this is not universalpractice. For details, see the module docstring.
Return value is adatetime instance in timezonetz (default torcparams TZ value).
Ifx is a sequence, a sequence ofdatetime objects willbe returned.
matplotlib.dates.drange(dstart,dend,delta)¶Return a date range as float Gregorian ordinals.dstart anddend aredatetime instances.delta is adatetime.timedelta instance.
matplotlib.dates.epoch2num(e)¶Convert an epoch or sequence of epochs to the new date format,that is days since 0001.
matplotlib.dates.num2epoch(d)¶Convert days since 0001 to epoch.d can be a number or sequence.
matplotlib.dates.mx2num(mxdates)¶Convert mxdatetime instance (or sequence of mxinstances) to the new date format.
matplotlib.dates.DateFormatter(fmt,tz=None)¶Bases:matplotlib.ticker.Formatter
Tick location is seconds since the epoch. Use astrftime()format string.
Python only supportsdatetimestrftime() formattingfor years greater than 1900. Thanks to Andrew Dalke, DalkeScientific Software who contributed thestrftime() codebelow to include dates earlier than this year.
strftime() format string;tz is thetzinfo instance.illegal_s = re.compile('((^|[^%])(%%)*%s)')¶set_tzinfo(tz)¶strftime(dt,fmt=None)¶Refer to documentation for datetime.strftime.
fmt is astrftime() format string.
Warning: For years before 1900, depending upon the currentlocale it is possible that the year displayed with %x mightbe incorrect. For years before 100, %y and %Y will yieldzero-padded strings.
strftime_pre_1900(dt,fmt=None)¶Call time.strftime for years before 1900 by rollingforward a multiple of 28 years.
fmt is astrftime() format string.
Dalke: I hope I did this math right. Every 28 years thecalendar repeats, except through century leap years exceptingthe 400 year leap years. But only if you’re using the Gregoriancalendar.
matplotlib.dates.IndexDateFormatter(t,fmt,tz=None)¶Bases:matplotlib.ticker.Formatter
Use withIndexLocator to cycle formatstrings by index.
t is a sequence of dates (floating point days).fmt is astrftime() format string.
matplotlib.dates.AutoDateFormatter(locator,tz=None,defaultfmt='%Y-%m-%d')¶Bases:matplotlib.ticker.Formatter
This class attempts to figure out the best format to use. This ismost useful when used with theAutoDateLocator.
The AutoDateFormatter has a scale dictionary that maps the scaleof the tick (the distance in days between one major tick) and aformat string. The default looks like this:
self.scaled={DAYS_PER_YEAR:rcParams['date.autoformat.year'],DAYS_PER_MONTH:rcParams['date.autoformat.month'],1.0: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 algorithm picks the key in the dictionary that is >= thecurrent scale and uses that format string. You can customize thisdictionary by doing:
>>>locator=AutoDateLocator()>>>formatter=AutoDateFormatter(locator)>>>formatter.scaled[1/(24.*60.)]='%M:%S'# only show min and sec
A customFuncFormatter can also be used.The following example shows how to use a custom format function to striptrailing zeros from decimal seconds and adds the date to the firstticklabel:
>>>defmy_format_function(x,pos=None):...x=matplotlib.dates.num2date(x)...ifpos==0:...fmt='%D %H:%M:%S.%f'...else:...fmt='%H:%M:%S.%f'...label=x.strftime(fmt)...label=label.rstrip("0")...label=label.rstrip(".")...returnlabel>>>frommatplotlib.tickerimportFuncFormatter>>>formatter.scaled[1/(24.*60.)]=FuncFormatter(my_format_function)
Autoformat the date labels. The default format is the one to useif none of the values inself.scaled are greater than the unitreturned bylocator._get_unit().
matplotlib.dates.DateLocator(tz=None)¶Bases:matplotlib.ticker.Locator
Determines the tick locations when plotting dates.
tz is atzinfo instance.
datalim_to_dt()¶Convert axis data interval to datetime objects.
hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}¶nonsingular(vmin,vmax)¶Given the proposed upper and lower extent, adjust the rangeif it is too close to being singular (i.e. a range of ~0).
set_tzinfo(tz)¶Set time zone info.
viewlim_to_dt()¶Converts the view interval to datetime objects.
matplotlib.dates.RRuleLocator(o,tz=None)¶Bases:matplotlib.dates.DateLocator
autoscale()¶Set the view limits to include the data range.
get_unit_generic(freq)¶tick_values(vmin,vmax)¶matplotlib.dates.AutoDateLocator(tz=None,minticks=5,maxticks=None,interval_multiples=False)¶Bases:matplotlib.dates.DateLocator
On autoscale, this class picks the bestDateLocator to set the view limits and the ticklocations.
minticks is the minimum number of ticks desired, which is used toselect the type of ticking (yearly, monthly, etc.).
maxticks is the maximum number of ticks desired, which controlsany interval between ticks (ticking every other, every 3, etc.).For really fine-grained control, this can be a dictionary mappingindividual rrule frequency constants (YEARLY, MONTHLY, etc.)to their own maximum number of ticks. This can be used to keepthe number of ticks appropriate to the format chosen inAutoDateFormatter. Any frequency not specified in thisdictionary is given a default value.
tz is atzinfo instance.
interval_multiples is a boolean that indicates whether ticksshould be chosen to be multiple of the interval. This will lockticks to ‘nicer’ locations. For example, this will force theticks to be at hours 0,6,12,18 when hourly ticking is done at6 hour intervals.
The AutoDateLocator has an interval dictionary that maps thefrequency of the tick (a constant from dateutil.rrule) and amultiple allowed for that ticking. The default looks like this:
self.intervald={YEARLY:[1,2,4,5,10,20,40,50,100,200,400,500,1000,2000,4000,5000,10000],MONTHLY:[1,2,3,4,6],DAILY:[1,2,3,7,14],HOURLY:[1,2,3,4,6,12],MINUTELY:[1,5,10,15,30],SECONDLY:[1,5,10,15,30],MICROSECONDLY:[1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000,200000,500000,1000000],}
The interval is used to specify multiples that are appropriate forthe frequency of ticking. For instance, every 7 days is sensiblefor daily ticks, but for minutes/seconds, 15 or 30 make sense.You can customize this dictionary by doing:
locator=AutoDateLocator()locator.intervald[HOURLY]=[3]# only show every 3 hours
autoscale()¶Try to choose the view limits intelligently.
get_locator(dmin,dmax)¶Pick the best locator based on a distance.
nonsingular(vmin,vmax)¶refresh()¶Refresh internal information based on current limits.
set_axis(axis)¶tick_values(vmin,vmax)¶matplotlib.dates.YearLocator(base=1,month=1,day=1,tz=None)¶Bases:matplotlib.dates.DateLocator
Make ticks on a given day of each year that is a multiple of base.
Examples:
# Tick every year on Jan 1stlocator=YearLocator()# Tick every 5 years on July 4thlocator=YearLocator(5,month=7,day=4)
Mark years that are multiple of base on a given month and day(default jan 1).
autoscale()¶Set the view limits to include the data range.
tick_values(vmin,vmax)¶matplotlib.dates.MonthLocator(bymonth=None,bymonthday=1,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each month month, e.g., 1, 3, 12.
Mark every month inbymonth;bymonth can be an int orsequence. Default isrange(1,13), i.e. every month.
interval is the interval between each iteration. Forexample, ifinterval=2, mark every second occurance.
matplotlib.dates.WeekdayLocator(byweekday=1,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each weekday.
Mark every weekday inbyweekday;byweekday can be a number orsequence.
Elements ofbyweekday must be one of MO, TU, WE, TH, FR, SA,SU, the constants fromdateutil.rrule, which have beenimported into thematplotlib.dates namespace.
interval specifies the number of weeks to skip. For example,interval=2 plots every second week.
matplotlib.dates.DayLocator(bymonthday=None,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each day of the month. For example,1, 15, 30.
Mark every day inbymonthday;bymonthday can be an int orsequence.
Default is to tick every day of the month:bymonthday=range(1,32)
matplotlib.dates.HourLocator(byhour=None,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each hour.
Mark every hour inbyhour;byhour can be an int or sequence.Default is to tick every hour:byhour=range(24)
interval is the interval between each iteration. Forexample, ifinterval=2, mark every second occurrence.
matplotlib.dates.MinuteLocator(byminute=None,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each minute.
Mark every minute inbyminute;byminute can be an int orsequence. Default is to tick every minute:byminute=range(60)
interval is the interval between each iteration. Forexample, ifinterval=2, mark every second occurrence.
matplotlib.dates.SecondLocator(bysecond=None,interval=1,tz=None)¶Bases:matplotlib.dates.RRuleLocator
Make ticks on occurances of each second.
Mark every second inbysecond;bysecond can be an int orsequence. Default is to tick every second:bysecond=range(60)
interval is the interval between each iteration. Forexample, ifinterval=2, mark every second occurrence.
matplotlib.dates.MicrosecondLocator(interval=1,tz=None)¶Bases:matplotlib.dates.DateLocator
Make ticks on occurances of each microsecond.
interval is the interval between each iteration. Forexample, ifinterval=2, mark every second microsecond.
set_axis(axis)¶set_data_interval(vmin,vmax)¶set_view_interval(vmin,vmax)¶tick_values(vmin,vmax)¶matplotlib.dates.rrule(freq,dtstart=None,interval=1,wkst=None,count=None,until=None,bysetpos=None,bymonth=None,bymonthday=None,byyearday=None,byeaster=None,byweekno=None,byweekday=None,byhour=None,byminute=None,bysecond=None,cache=False)¶Bases:dateutil.rrule.rrulebase
That’s the base of the rrule operation. It accepts all the keywordsdefined in the RFC as its constructor parameters (except byday,which was renamed to byweekday) and more. The constructor prototype is:
rrule(freq)
Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,or SECONDLY.
Note
Per RFC section 3.3.10, recurrence instances falling on invalid datesand times are ignored rather than coerced:
Recurrence rules may generate recurrence instances with an invaliddate (e.g., February 30) or nonexistent local time (e.g., 1:30 AMon a day where the local time is moved forward by an hour at 1:00AM). Such recurrence instances MUST be ignored and MUST NOT becounted as part of the recurrence set.
This can lead to possibly surprising behavior when, for example, thestart date occurs at the end of the month:
>>>fromdateutil.rruleimportrrule,MONTHLY>>>fromdatetimeimportdatetime>>>start_date=datetime(2014,12,31)>>>list(rrule(freq=MONTHLY,count=4,dtstart=start_date))...[datetime.datetime(2014, 12, 31, 0, 0), datetime.datetime(2015, 1, 31, 0, 0), datetime.datetime(2015, 3, 31, 0, 0), datetime.datetime(2015, 5, 31, 0, 0)]
Additionally, it supports the following keyword arguments:
| Parameters: |
|
|---|
replace(**kwargs)¶Return new rrule with same attributes except for those attributes given newvalues by whichever keyword arguments are specified.
matplotlib.dates.relativedelta(dt1=None,dt2=None,years=0,months=0,days=0,leapdays=0,weeks=0,hours=0,minutes=0,seconds=0,microseconds=0,year=None,month=None,day=None,weekday=None,yearday=None,nlyearday=None,hour=None,minute=None,second=None,microsecond=None)¶Bases:object
The relativedelta type is based on the specification of the excellentwork done by M.-A. Lemburg in hismx.DateTime extension.However, notice that this type doesNOT implement the same algorithm ashis work. DoNOT expect it to behave like mx.DateTime’s counterpart.
There are two different ways to build a relativedelta instance. Thefirst one is passing it two date/datetime classes:
relativedelta(datetime1,datetime2)
The second one is passing it any number of the following keyword arguments:
relativedelta(arg1=x,arg2=y,arg3=z...)year,month,day,hour,minute,second,microsecond:Absoluteinformation(argumentissingular);addingorsubtractingarelativedeltawithabsoluteinformationdoesnotperformanaritmeticoperation,butratherREPLACESthecorrespondingvalueintheoriginaldatetimewiththevalue(s)inrelativedelta.years,months,weeks,days,hours,minutes,seconds,microseconds:Relativeinformation,maybenegative(argumentisplural);addingorsubtractingarelativedeltawithrelativeinformationperformsthecorrespondingaritmeticoperationontheoriginaldatetimevaluewiththeinformationintherelativedelta.weekday:Oneoftheweekdayinstances(MO,TU,etc).TheseinstancesmayreceiveaparameterN,specifyingtheNthweekday,whichcouldbepositiveornegative(likeMO(+1)orMO(-2).Notspecifyingitisthesameasspecifying+1.Youcanalsouseaninteger,where0=MO.leapdays:Willaddgivendaystothedatefound,ifyearisaleapyear,andthedatefoundispost28offebruary.yearday,nlyearday:Settheyeardayorthenon-leapyearday(jumpleapdays).Theseareconvertedtoday/month/leapdaysinformation.
Here is the behavior of operations with relativedelta:
normalized()¶Return a version of this object represented entirely using integervalues for the relative attributes.
>>>relativedelta(days=1.5,hours=2).normalized()relativedelta(days=1, hours=14)
| Returns: | Returns adateutil.relativedelta.relativedelta object. |
|---|
weeks¶matplotlib.dates.seconds(s)¶Return seconds as days.
matplotlib.dates.minutes(m)¶Return minutes as days.
matplotlib.dates.hours(h)¶Return hours as days.
matplotlib.dates.weeks(w)¶Return weeks as days.