matplotlib.dates#

Inheritance diagram of matplotlib.dates

Matplotlib provides sophisticated date plotting capabilities, standing on theshoulders of pythondatetime and the add-on moduledateutil.

By default, Matplotlib uses the units machinery described inunits to convertdatetime.datetime, andnumpy.datetime64objects when plotted on an x- or y-axis. The user does notneed to do anything for dates to be formatted, but dates often have strictformatting needs, so this module provides many tick locators and formatters.A basic example usingnumpy.datetime64 is:

importnumpyasnptimes=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)

Matplotlib date format#

Matplotlib represents dates using floating point numbers specifying the numberof 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 andlocators require the use ofdatetime.datetime objects, so only dates betweenyear 0001 and 9999 can be represented. Microsecond precisionis achievable for (approximately) 70 years on either side of the epoch, and20 microseconds for the rest of the allowable range of dates (year 0001 to9999). The epoch can be changed at import time viadates.set_epoch orrcParams["date.epoch"] (default:'1970-01-01T00:00:00') to other dates if necessary; seeDate precision and epochs for a discussion.

Note

Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modernmicrosecond precision and also made the default axis limit of 0 an invaliddatetime. In 3.3 the epoch was changed as above. To convert oldordinal 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 betweendatetimeobjects and Matplotlib dates:

datestr2num

Convert a date string to a datenum usingdateutil.parser.parse.

date2num

Convert datetime objects to Matplotlib dates.

num2date

Convert Matplotlib dates todatetime objects.

num2timedelta

Convert number of days to atimedelta object.

drange

Return a sequence of equally spaced Matplotlib dates.

set_epoch

Set the epoch (origin for dates) for datetime calculations.

get_epoch

Get the epoch used bydates.

Note

Like Python'sdatetime.datetime, Matplotlib uses the Gregorian calendarfor all conversions between dates and floating point numbers. This practiceis not universal, and calendar differences can cause confusingdifferences between what Python and Matplotlib 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[1]:date(2006,4,1).toordinal()-date(1,1,1).toordinal()Out[1]:732401

All the Matplotlib date converters, locators and formatters are timezone aware.If no explicit timezone is provided,rcParams["timezone"] (default:'UTC') is assumed, provided as astring. If you want to use a different timezone, pass thetz keywordargument ofnum2date to any date tick locators or formatters you create. Thiscan be either adatetime.tzinfo instance or a string with the timezone namethat can be parsed bygettz.

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.

Thedateutil module provides additional code to handle date ticking, making iteasy to place ticks on any kinds of dates. See examples below.

Date tick locators#

Most of the date tick locators can locate single or multiple ticks. For example:

# 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)

The available date tick locators are:

Date formatters#

The available date formatters are:

classmatplotlib.dates.AutoDateFormatter(locator,tz=None,defaultfmt='%Y-%m-%d',*,usetex=None)[source]#

Bases:Formatter

AFormatter which attempts to figure out the best format to use. Thisis most useful when used with theAutoDateLocator.

AutoDateFormatter has a.scale dictionary that maps tick scales (theinterval in days between one major tick) to format strings; this dictionarydefaults to

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'],}

The formatter uses the format string corresponding to the lowest key inthe dictionary that is greater or equal to the current scale. Dictionaryentries 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 followingexample shows how to use a custom format function to strip trailing zerosfrom decimal seconds and adds the date to the first ticklabel:

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(".")returnlabelformatter.scaled[1/(24*60)]=my_format_function

Autoformat the date labels.

Parameters:
locatorticker.Locator

Locator that this axis is using.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

defaultfmtstr

The default format to use if none of the values inself.scaledare greater than the unit returned bylocator._get_unit().

usetexbool, default:rcParams["text.usetex"] (default:False)

To enable/disable the use of TeX's math mode for rendering theresults of the formatter. If any entries inself.scaled are setas functions, then it is up to the customized function to enable ordisable TeX's math mode itself.

classmatplotlib.dates.AutoDateLocator(tz=None,minticks=5,maxticks=None,interval_multiples=True)[source]#

Bases:DateLocator

On autoscale, this class picks the bestDateLocator to set the viewlimits and the tick locations.

Attributes:
intervalddict

Mapping of tick frequencies to multiples allowed for that ticking.The default is

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,21],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],}

where the keys are defined indateutil.rrule.

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.

When customizing, you should only modify the values for the existingkeys. You should not add or delete entries.

Example for forcing ticks every 3 hours:

locator=AutoDateLocator()locator.intervald[HOURLY]=[3]# only show every 3 hours
Parameters:
tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

minticksint

The minimum number of ticks desired; controls whether ticks occuryearly, monthly, etc.

maxticksint

The maximum number of ticks desired; controls the interval betweenticks (ticking every other, every 3, etc.). For fine-grainedcontrol, this can be a dictionary mapping individual rrulefrequency constants (YEARLY, MONTHLY, etc.) to their own maximumnumber of ticks. This can be used to keep the number of ticksappropriate to the format chosen inAutoDateFormatter. Anyfrequency not specified in this dictionary is given a defaultvalue.

interval_multiplesbool, default: True

Whether ticks should be chosen to be multiple of the interval,locking them to 'nicer' locations. For example, this will forcethe ticks to be at hours 0, 6, 12, 18 when hourly ticking is doneat 6 hour intervals.

get_locator(dmin,dmax)[source]#

Pick the best locator based on a distance.

nonsingular(vmin,vmax)[source]#

Given the proposed upper and lower extent, adjust the rangeif it is too close to being singular (i.e. a range of ~0).

tick_values(vmin,vmax)[source]#

Return the values of the located ticks givenvmin andvmax.

Note

To get tick locations with the vmin and vmax values definedautomatically for the associatedaxis simply callthe Locator instance:

>>>print(type(loc))<type 'Locator'>>>>print(loc())[1, 2, 3, 4]
classmatplotlib.dates.ConciseDateConverter(formats=None,zero_formats=None,offset_formats=None,show_offset=True,*,interval_multiples=True)[source]#

Bases:DateConverter

axisinfo(unit,axis)[source]#

Return theAxisInfo forunit.

unit is atzinfo instance or None.Theaxis argument is required but not used.

classmatplotlib.dates.ConciseDateFormatter(locator,tz=None,formats=None,offset_formats=None,zero_formats=None,show_offset=True,*,usetex=None)[source]#

Bases:Formatter

AFormatter which attempts to figure out the best format to use for thedate, and to make it as compact as possible, but still be complete. This ismost useful when used with theAutoDateLocator:

>>>locator=AutoDateLocator()>>>formatter=ConciseDateFormatter(locator)
Parameters:
locatorticker.Locator

Locator that this axis is using.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone, passed todates.num2date.

formatslist of 6 strings, optional

Format strings for 6 levels of tick labelling: mostly years,months, days, hours, minutes, and seconds. Strings usethe same format codes asstrftime. Default is['%Y','%b','%d','%H:%M','%H:%M','%S.%f']

zero_formatslist of 6 strings, optional

Format strings for tick labels that are "zeros" for a given ticklevel. For instance, if most ticks are months, ticks around 1 Jan 2005will be labeled "Dec", "2005", "Feb". The default is['','%Y','%b','%b-%d','%H:%M','%H:%M']

offset_formatslist 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 thedate. The default is:

['','%Y','%Y-%b','%Y-%b-%d','%Y-%b-%d','%Y-%b-%d %H:%M']
show_offsetbool, default: True

Whether to show the offset or not.

usetexbool, default:rcParams["text.usetex"] (default:False)

To enable/disable the use of TeX's math mode for rendering the resultsof the formatter.

Examples

SeeFormat date ticks using ConciseDateFormatter

(Sourcecode,2x.png,png)

Autoformat the date labels. The default format is used to form aninitial string, and then redundant elements are removed.

format_data_short(value)[source]#

Return a short string version of the tick value.

Defaults to the position-independent long value.

format_ticks(values)[source]#

Return the tick labels for all the ticks at once.

get_offset()[source]#
classmatplotlib.dates.DateConverter(*,interval_multiples=True)[source]#

Bases:ConversionInterface

Converter fordatetime.date anddatetime.datetime data, or fordate/time data represented as it would be converted bydate2num.

The 'unit' tag for such data is None or atzinfo instance.

axisinfo(unit,axis)[source]#

Return theAxisInfo forunit.

unit is atzinfo instance or None.Theaxis argument is required but not used.

staticconvert(value,unit,axis)[source]#

Ifvalue is not already a number or sequence of numbers, convert itwithdate2num.

Theunit andaxis arguments are not used.

staticdefault_units(x,axis)[source]#

Return thetzinfo instance ofx or of its first element,or None

classmatplotlib.dates.DateFormatter(fmt,tz=None,*,usetex=None)[source]#

Bases:Formatter

Format a tick (in days since the epoch) with astrftime format string.

Parameters:
fmtstr

strftime format string

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

usetexbool, default:rcParams["text.usetex"] (default:False)

To enable/disable the use of TeX's math mode for rendering theresults of the formatter.

set_tzinfo(tz)[source]#
classmatplotlib.dates.DateLocator(tz=None)[source]#

Bases:Locator

Determines the tick locations when plotting dates.

This class is subclassed by other Locators andis not meant to be used on its own.

Parameters:
tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

datalim_to_dt()[source]#

Convert axis data interval to datetime objects.

hms0d={'byhour':0,'byminute':0,'bysecond':0}#
nonsingular(vmin,vmax)[source]#

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)[source]#

Set timezone info.

Parameters:
tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

viewlim_to_dt()[source]#

Convert the view interval to datetime objects.

classmatplotlib.dates.DayLocator(bymonthday=None,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each day of the month. For example,1, 15, 30.

Parameters:
bymonthdayint or list of int, default: all days

Ticks will be placed on every day inbymonthday. Default isbymonthday=range(1,32), i.e., every day of the month.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.HourLocator(byhour=None,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each hour.

Parameters:
byhourint or list of int, default: all hours

Ticks will be placed on every hour inbyhour. Default isbyhour=range(24), i.e., every hour.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.MicrosecondLocator(interval=1,tz=None)[source]#

Bases:DateLocator

Make ticks on regular intervals of one or more microsecond(s).

Note

By default, Matplotlib uses a floating point representation of time indays since the epoch, so plotting data withmicrosecond time resolution does not work well fordates that are far (about 70 years) from the epoch (check withget_epoch).

If you want sub-microsecond resolution time plots, it is stronglyrecommended to use floating point seconds, not datetime-liketime representation.

If you really must use datetime.datetime() or similar and stillneed microsecond precision, change the time origin viadates.set_epoch to something closer to the dates being plotted.SeeDate precision and epochs.

Parameters:
intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

set_axis(axis)[source]#
tick_values(vmin,vmax)[source]#

Return the values of the located ticks givenvmin andvmax.

Note

To get tick locations with the vmin and vmax values definedautomatically for the associatedaxis simply callthe Locator instance:

>>>print(type(loc))<type 'Locator'>>>>print(loc())[1, 2, 3, 4]
classmatplotlib.dates.MinuteLocator(byminute=None,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each minute.

Parameters:
byminuteint or list of int, default: all minutes

Ticks will be placed on every minute inbyminute. Default isbyminute=range(60), i.e., every minute.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.MonthLocator(bymonth=None,bymonthday=1,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each month, e.g., 1, 3, 12.

Parameters:
bymonthint or list of int, default: all months

Ticks will be placed on every month inbymonth. Default isrange(1,13), i.e. every month.

bymonthdayint, default: 1

The day on which to place the ticks.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.RRuleLocator(o,tz=None)[source]#

Bases:DateLocator

Parameters:
tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

staticget_unit_generic(freq)[source]#
tick_values(vmin,vmax)[source]#

Return the values of the located ticks givenvmin andvmax.

Note

To get tick locations with the vmin and vmax values definedautomatically for the associatedaxis simply callthe Locator instance:

>>>print(type(loc))<type 'Locator'>>>>print(loc())[1, 2, 3, 4]
classmatplotlib.dates.SecondLocator(bysecond=None,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each second.

Parameters:
bysecondint or list of int, default: all seconds

Ticks will be placed on every second inbysecond. Default isbysecond=range(60), i.e., every second.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.WeekdayLocator(byweekday=1,interval=1,tz=None)[source]#

Bases:RRuleLocator

Make ticks on occurrences of each weekday.

Parameters:
byweekdayint or list of int, default: all days

Ticks will be placed on every weekday inbyweekday. Default isevery day.

Elements ofbyweekday must be one of MO, TU, WE, TH, FR, SA,SU, the constants fromdateutil.rrule, which have beenimported into thematplotlib.dates namespace.

intervalint, default: 1

The interval between each iteration. For example, ifinterval=2, mark every second occurrence.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

classmatplotlib.dates.YearLocator(base=1,month=1,day=1,tz=None)[source]#

Bases:RRuleLocator

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)
Parameters:
baseint, default: 1

Mark ticks everybase years.

monthint, default: 1

The month on which to place the ticks, starting from 1. Default isJanuary.

dayint, default: 1

The day on which to place the ticks.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Ticks timezone. If a string,tz is passed todateutil.tz.

matplotlib.dates.date2num(d)[source]#

Convert datetime objects to Matplotlib dates.

Parameters:
ddatetime.datetime ornumpy.datetime64 or sequences of these
Returns:
float or sequence of floats

Number of days since the epoch. Seeget_epoch for theepoch, which can be changed byrcParams["date.epoch"] (default:'1970-01-01T00:00:00') orset_epoch. Ifthe 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.

matplotlib.dates.datestr2num(d,default=None)[source]#

Convert a date string to a datenum usingdateutil.parser.parse.

Parameters:
dstr or sequence of str

The dates to convert.

defaultdatetime.datetime, optional

The default date to use when fields are missing ind.

matplotlib.dates.drange(dstart,dend,delta)[source]#

Return a sequence of equally spaced Matplotlib dates.

The dates start atdstart and reach up to, but not includingdend.They are spaced bydelta.

Parameters:
dstart, denddatetime

The date limits.

deltadatetime.timedelta

Spacing of the dates.

Returns:
numpy.array

A list floats representing Matplotlib dates.

matplotlib.dates.get_epoch()[source]#

Get the epoch used bydates.

Returns:
epochstr

String for the epoch (parsable bynumpy.datetime64).

matplotlib.dates.num2date(x,tz=None)[source]#

Convert Matplotlib dates todatetime objects.

Parameters:
xfloat or sequence of floats

Number of days (fraction part represents hours, minutes, seconds)since the epoch. Seeget_epoch for theepoch, which can be changed byrcParams["date.epoch"] (default:'1970-01-01T00:00:00') orset_epoch.

tzstr ortzinfo, default:rcParams["timezone"] (default:'UTC')

Timezone ofx. If a string,tz is passed todateutil.tz.

Returns:
datetime or sequence ofdatetime

Dates are returned in timezonetz.

Ifx is a sequence, a sequence ofdatetime objects willbe returned.

Notes

The Gregorian calendar is assumed; this is not universal practice.For details, see the module docstring.

matplotlib.dates.num2timedelta(x)[source]#

Convert number of days to atimedelta object.

Ifx is a sequence, a sequence oftimedelta objects willbe returned.

Parameters:
xfloat, sequence of floats

Number of days. The fraction part represents hours, minutes, seconds.

Returns:
datetime.timedelta or list[datetime.timedelta]
classmatplotlib.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 designed to be applied to an existing datetime andcan replace specific components of that datetime, or represents an intervalof time.

It is based on the specification of the excellent work done by M.-A. Lemburgin 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);addingorsubtractingarelativedeltawithabsoluteinformationdoesnotperformanarithmeticoperation,butratherREPLACESthecorrespondingvalueintheoriginaldatetimewiththevalue(s)inrelativedelta.years,months,weeks,days,hours,minutes,seconds,microseconds:Relativeinformation,maybenegative(argumentisplural);addingorsubtractingarelativedeltawithrelativeinformationperformsthecorrespondingarithmeticoperationontheoriginaldatetimevaluewiththeinformationintherelativedelta.weekday:Oneoftheweekdayinstances(MO,TU,etc)availableintherelativedeltamodule.TheseinstancesmayreceiveaparameterN,specifyingtheNthweekday,whichcouldbepositiveornegative(likeMO(+1)orMO(-2)).Notspecifyingitisthesameasspecifying+1.Youcanalsouseaninteger,where0=MO.Thisargumentisalwaysrelativee.g.ifthecalculateddateisalreadyMonday,usingMO(1)orMO(-1)won't change the day. To effectively make it absolute, useitincombinationwiththedayargument(e.g.day=1,MO(1)forfirstMondayofthemonth).leapdays:Willaddgivendaystothedatefound,ifyearisaleapyear,andthedatefoundispost28offebruary.yearday,nlyearday:Settheyeardayorthenon-leapyearday(jumpleapdays).Theseareconvertedtoday/month/leapdaysinformation.

There are relative and absolute forms of the keywordarguments. The plural is relative, and the singular isabsolute. For each argument in the order below, the absolute formis applied first (by setting each attribute to that value) andthen the relative form (by adding the value to the attribute).

The order of attributes considered when this relativedelta isadded to a datetime is:

  1. Year

  2. Month

  3. Day

  4. Hours

  5. Minutes

  6. Seconds

  7. Microseconds

Finally, weekday is applied, using the rule described above.

For example

>>>fromdatetimeimportdatetime>>>fromdateutil.relativedeltaimportrelativedelta,MO>>>dt=datetime(2018,4,9,13,37,0)>>>delta=relativedelta(hours=25,day=1,weekday=MO(1))>>>dt+deltadatetime.datetime(2018, 4, 2, 14, 37)

First, the day is set to 1 (the first of the month), then 25 hoursare added, to get to the 2nd day and 14th hour, finally theweekday is applied, but since the 2nd is already a Monday there isno effect.

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.

propertyweeks#
classmatplotlib.dates.rrulewrapper(freq,tzinfo=None,**kwargs)[source]#

Bases:object

A simple wrapper around adateutil.rrule allowing flexibledate tick specifications.

Parameters:
freq{YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY}

Tick frequency. These constants are defined indateutil.rrule,but they are accessible frommatplotlib.dates as well.

tzinfodatetime.tzinfo, optional

Time zone information. The default is None.

**kwargs

Additional keyword arguments are passed to thedateutil.rrule.

set(**kwargs)[source]#

Set parameters for an existing wrapper.

matplotlib.dates.set_epoch(epoch)[source]#

Set the epoch (origin for dates) for datetime calculations.

The default epoch isrcParams["date.epoch"] (default:'1970-01-01T00:00:00').

If microsecond accuracy is desired, the date being plotted needs to bewithin approximately 70 years of the epoch. Matplotlib internallyrepresents dates as days since the epoch, so floating point dynamicrange needs to be within a factor of 2^52.

set_epoch must be called before any dates are converted(i.e. near the import section) or a RuntimeError will be raised.

See alsoDate precision and epochs.

Parameters:
epochstr

valid UTC date parsable bynumpy.datetime64 (do not includetimezone).

On this page