Contents
Thedateutil module provides powerful extensions tothe standarddatetime module, available in Python 2.3+.
iCalendarspecification. Parsing of RFC strings is supported as well.
Here's a snapshot, just to give an idea about the power of thepackage. For more examples, look at the documentation below.
Suppose you want to know how much time is left, inyears/months/days/etc, before the next easter happening on ayear with a Friday 13th in August, and you want to get today'sdate out of the "date" unix system command. Here is the code:
from dateutil.relativedelta import *from dateutil.easter import *from dateutil.rrule import *from dateutil.parser import *from datetime import *import commandsimport osnow = parse(commands.getoutput("date"))today = now.date()year = rrule(YEARLY,bymonth=8,bymonthday=13,byweekday=FR)[0].yearrdelta = relativedelta(easter(year), today)print "Today is:", todayprint "Year with next Aug 13th on a Friday is:", yearprint "How far is the Easter of that year:", rdeltaprint "And the Easter of that year is:", today+rdelta
And here's the output:
Today is: 2003-10-11Year with next Aug 13th on a Friday is: 2004How far is the Easter of that year: relativedelta(months=+6)And the Easter of that year is: 2004-04-11
Being exactly 6 months ahead wasreally a coincidence
Development is currently maintained in Launchpad:
The following files are available.
python-dateutil-2.0.tar.gz (Python >= 3.0)
python-dateutil-1.5.tar.gz (Python < 3.0)
The dateutil module was written by Gustavo Niemeyer <gustavo@niemeyer.net>.
The following modules are available.
This module offers therelativedelta type, which is basedon the specification of the excelent work done by M.-A. Lemburg in hismxDateTimeextension. However, notice that this typedoes not implement thesame algorithm as his work. Do not expect it to behave likemxDateTime's counterpart.
There's two different ways to build a relativedelta instance. Thefirst one is passing it twodate/datetime instances:
relativedelta(datetime1, datetime2)
This will build the relative difference betweendatetime1 anddatetime2, so that the following constraint is always true:
datetime2+relativedelta(datetime1, datetime2) == datetime1
Notice that instead ofdatetime instances, you may usedate instances, or a mix of both.
And the other way is to use any of the following keyword arguments:
One of the weekday instances (MO,TU, etc). Theseinstances may receive a parametern, specifying thenthweekday, which could be positive or negative (likeMO(+2) orMO(-3). Not specifying it is the same as specifying+1.You can also use an integer, where0=MO. Notice that,for example, if the calculated date is already Monday, usingMO orMO(+1) (which is the same thing in this context),won't change the day.
These are converted today/month/leapdaysinformation.
If you're curious about how exactly the relative delta will acton operations, here is a description of its behavior.
Calculate the absolute year, using theyear argument, or the original datetime year, if the argument is not present.
Add the relativeyears argument to the absolute year.
Do steps 1 and 2 formonth/months.
Calculate the absolute day, using theday argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations.
Add the relativedays argument to the absolute day. Notice that theweeks argument is multiplied by 7 and added todays.
Ifleapdays is present, the computed year is a leap year, and the computed month is after february, remove one day from the found date.
Do steps 1 and 2 forhour/hours,minute/minutes,second/seconds,microsecond/microseconds.
If theweekday argument is present, calculate thenth occurrence of the given weekday.
Let's begin our trip.
>>> from datetime import *; from dateutil.relativedelta import *>>> import calendar
Store some values.
>>> NOW = datetime.now()>>> TODAY = date.today()>>> NOWdatetime.datetime(2003, 9, 17, 20, 54, 47, 282310)>>> TODAYdatetime.date(2003, 9, 17)
Next month.
>>> NOW+relativedelta(months=+1)datetime.datetime(2003, 10, 17, 20, 54, 47, 282310)
Next month, plus one week.
>>> NOW+relativedelta(months=+1, weeks=+1)datetime.datetime(2003, 10, 24, 20, 54, 47, 282310)
Next month, plus one week, at 10am.
>>> TODAY+relativedelta(months=+1, weeks=+1, hour=10)datetime.datetime(2003, 10, 24, 10, 0)
Let's try the other way around. Notice that thehour setting we get in the relativedelta is relative,since it's a difference, and the weeks parameterhas gone.
>>> relativedelta(datetime(2003, 10, 24, 10, 0), TODAY)relativedelta(months=+1, days=+7, hours=+10)
One month before one year.
>>> NOW+relativedelta(years=+1, months=-1)datetime.datetime(2004, 8, 17, 20, 54, 47, 282310)
How does it handle months with different numbers of days?Notice that adding one month will never cross the monthboundary.
>>> date(2003,1,27)+relativedelta(months=+1)datetime.date(2003, 2, 27)>>> date(2003,1,31)+relativedelta(months=+1)datetime.date(2003, 2, 28)>>> date(2003,1,31)+relativedelta(months=+2)datetime.date(2003, 3, 31)
The logic for years is the same, even on leap years.
>>> date(2000,2,28)+relativedelta(years=+1)datetime.date(2001, 2, 28)>>> date(2000,2,29)+relativedelta(years=+1)datetime.date(2001, 2, 28)>>> date(1999,2,28)+relativedelta(years=+1)datetime.date(2000, 2, 28)>>> date(1999,3,1)+relativedelta(years=+1)datetime.date(2000, 3, 1)>>> date(2001,2,28)+relativedelta(years=-1)datetime.date(2000, 2, 28)>>> date(2001,3,1)+relativedelta(years=-1)datetime.date(2000, 3, 1)
Next friday.
>>> TODAY+relativedelta(weekday=FR)datetime.date(2003, 9, 19)>>> TODAY+relativedelta(weekday=calendar.FRIDAY)datetime.date(2003, 9, 19)
Last friday in this month.
>>> TODAY+relativedelta(day=31, weekday=FR(-1))datetime.date(2003, 9, 26)
Next wednesday (it's today!).
>>> TODAY+relativedelta(weekday=WE(+1))datetime.date(2003, 9, 17)
Next wednesday, but not today.
>>> TODAY+relativedelta(days=+1, weekday=WE(+1))datetime.date(2003, 9, 24)
FollowingISO year week number notationfind the first day of the 15th week of 1997.
>>> datetime(1997,1,1)+relativedelta(day=4, weekday=MO(-1), weeks=+14)datetime.datetime(1997, 4, 7, 0, 0)
How long ago has the millennium changed?
>>> relativedelta(NOW, date(2001,1,1))relativedelta(years=+2, months=+8, days=+16, hours=+20, minutes=+54, seconds=+47, microseconds=+282310)
How old is John?
>>> johnbirthday = datetime(1978, 4, 5, 12, 0)>>> relativedelta(NOW, johnbirthday)relativedelta(years=+25, months=+5, days=+12, hours=+8, minutes=+54, seconds=+47, microseconds=+282310)
It works with dates too.
>>> relativedelta(TODAY, johnbirthday)relativedelta(years=+25, months=+5, days=+11, hours=+12)
Obtain today's date using the yearday:
>>> date(2003, 1, 1)+relativedelta(yearday=260)datetime.date(2003, 9, 17)
We can use today's date, since yearday should be absolutein the given year:
>>> TODAY+relativedelta(yearday=260)datetime.date(2003, 9, 17)
Last year it should be in the same day:
>>> date(2002, 1, 1)+relativedelta(yearday=260)datetime.date(2002, 9, 17)
But not in a leap year:
>>> date(2000, 1, 1)+relativedelta(yearday=260)datetime.date(2000, 9, 16)
We can use the non-leap year day to ignore this:
>>> date(2000, 1, 1)+relativedelta(nlyearday=260)datetime.date(2000, 9, 17)
The rrule module offers a small, complete, and very fast, implementationof the recurrence rules documented in theiCalendar RFC, includingsupport for caching of results.
That's the base of the rrule operation. It accepts all the keywordsdefined in the RFC as its constructor parameters (exceptbyday,which was renamed tobyweekday) and more. The constructorprototype is:
rrule(freq)
Wherefreq must be one ofYEARLY,MONTHLY,WEEKLY,DAILY,HOURLY,MINUTELY,orSECONDLY.
Additionally, it supports the following keyword arguments:
rrule instance multiple times, enabling caching willimprove the performance considerably.
given,datetime.now() will be used instead.
The interval between eachfreq iteration. For example,when usingYEARLY, an interval of2 meansonce every two years, but withHOURLY, it meansonce every two hours. The default interval is1.
The week start day. Must be one of theMO,TU,WE constants, or an integer, specifying the first dayof the week. This will affect recurrences based on weeklyperiods. The default week start is got fromcalendar.firstweekday(), and may be modified bycalendar.setfirstweekday().
If given, this must be adatetime instance, that willspecify the limit of the recurrence. If a recurrence instancehappens to be the same as thedatetime instance givenin theuntil keyword, this will be the last occurrence.
example, abysetpos of-1 if combined with aMONTHLY frequency, and abyweekday of(MO, TU, WE, TH, FR), will result in the last workday of every month.
If given, it must be either an integer (0 == MO), asequence of integers, one of the weekday constants(MO,TU, etc), or a sequence of these constants.When given, these variables will define the weekdays wherethe recurrence will be applied. It's also possible to usean argumentn for the weekday instances, which willmean thenth occurrence of this weekday in theperiod. For example, withMONTHLY, or withYEARLY andBYMONTH, usingFR(+1)inbyweekday will specify the first friday of themonth where the recurrence happens. Notice that in the RFCdocumentation, this is specified asBYDAY, but wasrenamed to avoid the ambiguity of that keyword.
0 tobyeaster will yield the Easter Sundayitself. This is an extension to the RFC specification.
The rrule frequency denotes the period on which the rule is evaluated.Multiple dates may match in a single period, and none may match as well,depending on the rule itself. In other words, the rule won't beadapted to ensure that a match necessarily happens inside the givenfrequency, and if multiple entries match the rule they will be returned.
Note, for instance, the two rules:
>>> list(rrule(DAILY, count=3, byweekday=(TU,TH),... dtstart=datetime(2007,1,1)))[datetime.datetime(2007, 1, 2, 0, 0), datetime.datetime(2007, 1, 4, 0, 0), datetime.datetime(2007, 1, 9, 0, 0)]>>> list(rrule(WEEKLY, count=3, byweekday=(TU,TH),... dtstart=datetime(2007,1,1)))[datetime.datetime(2007, 1, 2, 0, 0), datetime.datetime(2007, 1, 4, 0, 0), datetime.datetime(2007, 1, 9, 0, 0)]>>
In this case, they have the same meaning. The only difference isthe way that they were generated. Now, notice the change if weinclude abysetpos option.
>>> list(rrule(DAILY, count=3, byweekday=(TU,TH), bysetpos=1,... dtstart=datetime(2007,1,1)))[datetime.datetime(2007, 1, 2, 0, 0), datetime.datetime(2007, 1, 4, 0, 0), datetime.datetime(2007, 1, 9, 0, 0)]>>> list(rrule(WEEKLY, count=3, byweekday=(TU,TH), bysetpos=1,... dtstart=datetime(2007,1,1)))[datetime.datetime(2007, 1, 2, 0, 0), datetime.datetime(2007, 1, 9, 0, 0), datetime.datetime(2007, 1, 16, 0, 0)]
In both cases, only the first matching entryinside the given periodwas considered a match.
It is also important to note that specifying only the frequency willresult in the relevantbyXXX rule parts being retrieved from thedtstart value. For instance:
rrule(MONTHLY, dtstart=datetime(2007,1,2))
This would assumebymonthday=2,byhour=0,byminute=0, andso would generate date values for Jan 2nd, Feb 2nd, Mar 2nd, and so on. If,on the other hand, the start date is on Jan 31st:
rrule(MONTHLY, dtstart=datetime(2007,1,31))
This wouldonly generate values for 31st Jan, 31st Mar, 31st May, etc.Any month with less than 31 days isignored.
To generate a rrule for the use case of "a date on the specified day ofthe month, unless it is beyond the end of month, in which case it willbe the last day of the month" use the following:
rrule(MONTHLY, bymonthday=(some_day, -1), bysetpos=1)
This will generate a value for every calendar month regardless of theday of the month it is started from.
For more details, check theiCalendar RFC.
The following methods are available inrrule instances:
Returns the last recurrence before the givendatetimeinstance. Theinc keyword defines what happens ifdtis an occurrence. Withinc == True,ifdt itself is an occurrence, it will be returned.
Returns the first recurrence after the givendatetimeinstance. Theinc keyword defines what happens ifdtis an occurrence. Withinc == True,ifdt itself is an occurrence, it will be returned.
Returns all the occurrences of the rrule betweenafterandbefore. Theinc keyword defines what happensifafter and/orbefore are themselves occurrences.Withinc == True, they will be included in the list,if they are found in the recurrence set.
Besides these methods,rrule instances also supportthe__getitem__() and__contains__() special methods,meaning that these are valid expressions:
rr = rrule(...)if datetime(...) in rr: ...print rr[0]print rr[-1]print rr[1:2]print rr[::-2]
The getitem/slicing mechanism is smart enough to avoid getting the wholerecurrence set, if possible.
The rrule type has nobyday keyword. The equivalent keywordhas been replaced by thebyweekday keyword, to remove theambiguity present in the original keyword.
Unlike documented in the RFC, the starting datetime (dtstart)is not the first recurrence instance, unless it does fit in thespecified rules. In a python module context, this behavior makes moresense than otherwise. Notice that you can easily get the originalbehavior by using a rruleset and adding thedtstart as anrdate recurrence.
frequency (the RFC documents thatbyweekno is only validon yearly frequencies, for example).
In addition to the documented keywords, abyeaster keywordwas introduced, making it easy to compute recurrent events relativeto the Easter Sunday.
These examples were converted from the RFC.
Prepare the environment.
>>> from dateutil.rrule import *>>> from dateutil.parser import *>>> from datetime import *>>> import pprint>>> import sys>>> sys.displayhook = pprint.pprint
Daily, for 10 occurrences.
>>> list(rrule(DAILY, count=10, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0)]
Daily until December 24, 1997
>>> list(rrule(DAILY, dtstart=parse("19970902T090000"), until=parse("19971224T000000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), (...) datetime.datetime(1997, 12, 21, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1997, 12, 23, 9, 0)]
Every other day, 5 occurrences.
>>> list(rrule(DAILY, interval=2, count=5, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 10, 9, 0)]
Every 10 days, 5 occurrences.
>>> list(rrule(DAILY, interval=10, count=5, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)]
Everyday in January, for 3 years.
>>> list(rrule(YEARLY, bymonth=1, byweekday=range(7), dtstart=parse("19980101T090000"), until=parse("20000131T090000")))[datetime.datetime(1998, 1, 1, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), (...) datetime.datetime(1998, 1, 30, 9, 0), datetime.datetime(1998, 1, 31, 9, 0), datetime.datetime(1999, 1, 1, 9, 0), datetime.datetime(1999, 1, 2, 9, 0), (...) datetime.datetime(1999, 1, 30, 9, 0), datetime.datetime(1999, 1, 31, 9, 0), datetime.datetime(2000, 1, 1, 9, 0), datetime.datetime(2000, 1, 2, 9, 0), (...) datetime.datetime(2000, 1, 29, 9, 0), datetime.datetime(2000, 1, 31, 9, 0)]
Same thing, in another way.
>>> list(rrule(DAILY, bymonth=1, dtstart=parse("19980101T090000"), until=parse("20000131T090000")))(...)
Weekly for 10 occurrences.
>>> list(rrule(WEEKLY, count=10, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 21, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)]
Every other week, 6 occurrences.
>>> list(rrule(WEEKLY, interval=2, count=6, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 11, 9, 0)]
Weekly on Tuesday and Thursday for 5 weeks.
>>> list(rrule(WEEKLY, count=10, wkst=SU, byweekday=(TU,TH), dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 25, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0)]
Every other week on Tuesday and Thursday, for 8 occurrences.
>>> list(rrule(WEEKLY, interval=2, count=8, wkst=SU, byweekday=(TU,TH), dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 16, 9, 0)]
Monthly on the 1st Friday for ten occurrences.
>>> list(rrule(MONTHLY, count=10, byweekday=FR(1), dtstart=parse("19970905T090000")))[datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 10, 3, 9, 0), datetime.datetime(1997, 11, 7, 9, 0), datetime.datetime(1997, 12, 5, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), datetime.datetime(1998, 2, 6, 9, 0), datetime.datetime(1998, 3, 6, 9, 0), datetime.datetime(1998, 4, 3, 9, 0), datetime.datetime(1998, 5, 1, 9, 0), datetime.datetime(1998, 6, 5, 9, 0)]
Every other month on the 1st and last Sunday of the month for 10 occurrences.
>>> list(rrule(MONTHLY, interval=2, count=10, byweekday=(SU(1), SU(-1)), dtstart=parse("19970907T090000")))[datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 11, 2, 9, 0), datetime.datetime(1997, 11, 30, 9, 0), datetime.datetime(1998, 1, 4, 9, 0), datetime.datetime(1998, 1, 25, 9, 0), datetime.datetime(1998, 3, 1, 9, 0), datetime.datetime(1998, 3, 29, 9, 0), datetime.datetime(1998, 5, 3, 9, 0), datetime.datetime(1998, 5, 31, 9, 0)]
Monthly on the second to last Monday of the month for 6 months.
>>> list(rrule(MONTHLY, count=6, byweekday=MO(-2), dtstart=parse("19970922T090000")))[datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 20, 9, 0), datetime.datetime(1997, 11, 17, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1998, 1, 19, 9, 0), datetime.datetime(1998, 2, 16, 9, 0)]
Monthly on the third to the last day of the month, for 6 months.
>>> list(rrule(MONTHLY, count=6, bymonthday=-3, dtstart=parse("19970928T090000")))[datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 10, 29, 9, 0), datetime.datetime(1997, 11, 28, 9, 0), datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1998, 1, 29, 9, 0), datetime.datetime(1998, 2, 26, 9, 0)]
Monthly on the 2nd and 15th of the month for 5 occurrences.
>>> list(rrule(MONTHLY, count=5, bymonthday=(2,15), dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 15, 9, 0), datetime.datetime(1997, 11, 2, 9, 0)]
Monthly on the first and last day of the month for 3 occurrences.
>>> list(rrule(MONTHLY, count=5, bymonthday=(-1,1,), dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 1, 9, 0), datetime.datetime(1997, 10, 31, 9, 0), datetime.datetime(1997, 11, 1, 9, 0), datetime.datetime(1997, 11, 30, 9, 0)]
Every 18 months on the 10th thru 15th of the month for 10 occurrences.
>>> list(rrule(MONTHLY, interval=18, count=10, bymonthday=range(10,16), dtstart=parse("19970910T090000")))[datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 13, 9, 0), datetime.datetime(1997, 9, 14, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1999, 3, 10, 9, 0), datetime.datetime(1999, 3, 11, 9, 0), datetime.datetime(1999, 3, 12, 9, 0), datetime.datetime(1999, 3, 13, 9, 0)]
Every Tuesday, every other month, 6 occurences.
>>> list(rrule(MONTHLY, interval=2, count=6, byweekday=TU, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)]
Yearly in June and July for 10 occurrences.
>>> list(rrule(YEARLY, count=4, bymonth=(6,7), dtstart=parse("19970610T090000")))[datetime.datetime(1997, 6, 10, 9, 0), datetime.datetime(1997, 7, 10, 9, 0), datetime.datetime(1998, 6, 10, 9, 0), datetime.datetime(1998, 7, 10, 9, 0)]
Every 3rd year on the 1st, 100th and 200th day for 4 occurrences.
>>> list(rrule(YEARLY, count=4, interval=3, byyearday=(1,100,200), dtstart=parse("19970101T090000")))[datetime.datetime(1997, 1, 1, 9, 0), datetime.datetime(1997, 4, 10, 9, 0), datetime.datetime(1997, 7, 19, 9, 0), datetime.datetime(2000, 1, 1, 9, 0)]
Every 20th Monday of the year, 3 occurrences.
>>> list(rrule(YEARLY, count=3, byweekday=MO(20), dtstart=parse("19970519T090000")))[datetime.datetime(1997, 5, 19, 9, 0), datetime.datetime(1998, 5, 18, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)]
Monday of week number 20 (where the default start of the week is Monday),3 occurrences.
>>> list(rrule(YEARLY, count=3, byweekno=20, byweekday=MO, dtstart=parse("19970512T090000")))[datetime.datetime(1997, 5, 12, 9, 0), datetime.datetime(1998, 5, 11, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)]
The week number 1 may be in the last year.
>>> list(rrule(WEEKLY, count=3, byweekno=1, byweekday=MO, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1999, 1, 4, 9, 0), datetime.datetime(2000, 1, 3, 9, 0)]
And the week numbers greater than 51 may be in the next year.
>>> list(rrule(WEEKLY, count=3, byweekno=52, byweekday=SU, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 12, 28, 9, 0), datetime.datetime(1998, 12, 27, 9, 0), datetime.datetime(2000, 1, 2, 9, 0)]
Only some years have week number 53:
>>> list(rrule(WEEKLY, count=3, byweekno=53, byweekday=MO, dtstart=parse("19970902T090000")))[datetime.datetime(1998, 12, 28, 9, 0), datetime.datetime(2004, 12, 27, 9, 0), datetime.datetime(2009, 12, 28, 9, 0)]
Every Friday the 13th, 4 occurrences.
>>> list(rrule(YEARLY, count=4, byweekday=FR, bymonthday=13, dtstart=parse("19970902T090000")))[datetime.datetime(1998, 2, 13, 9, 0), datetime.datetime(1998, 3, 13, 9, 0), datetime.datetime(1998, 11, 13, 9, 0), datetime.datetime(1999, 8, 13, 9, 0)]
Every four years, the first Tuesday after a Monday in November,3 occurrences (U.S. Presidential Election day):
>>> list(rrule(YEARLY, interval=4, count=3, bymonth=11, byweekday=TU, bymonthday=(2,3,4,5,6,7,8), dtstart=parse("19961105T090000")))[datetime.datetime(1996, 11, 5, 9, 0), datetime.datetime(2000, 11, 7, 9, 0), datetime.datetime(2004, 11, 2, 9, 0)]
The 3rd instance into the month of one of Tuesday, Wednesday orThursday, for the next 3 months:
>>> list(rrule(MONTHLY, count=3, byweekday=(TU,WE,TH), bysetpos=3, dtstart=parse("19970904T090000")))[datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 11, 6, 9, 0)]
The 2nd to last weekday of the month, 3 occurrences.
>>> list(rrule(MONTHLY, count=3, byweekday=(MO,TU,WE,TH,FR), bysetpos=-2, dtstart=parse("19970929T090000")))[datetime.datetime(1997, 9, 29, 9, 0), datetime.datetime(1997, 10, 30, 9, 0), datetime.datetime(1997, 11, 27, 9, 0)]
Every 3 hours from 9:00 AM to 5:00 PM on a specific day.
>>> list(rrule(HOURLY, interval=3, dtstart=parse("19970902T090000"), until=parse("19970902T170000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 15, 0)]
Every 15 minutes for 6 occurrences.
>>> list(rrule(MINUTELY, interval=15, count=6, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 15), datetime.datetime(1997, 9, 2, 9, 30), datetime.datetime(1997, 9, 2, 9, 45), datetime.datetime(1997, 9, 2, 10, 0), datetime.datetime(1997, 9, 2, 10, 15)]
Every hour and a half for 4 occurrences.
>>> list(rrule(MINUTELY, interval=90, count=4, dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 10, 30), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 13, 30)]
Every 20 minutes from 9:00 AM to 4:40 PM for two days.
>>> list(rrule(MINUTELY, interval=20, count=48, byhour=range(9,17), byminute=(0,20,40), dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 20), (...) datetime.datetime(1997, 9, 2, 16, 20), datetime.datetime(1997, 9, 2, 16, 40), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 3, 9, 20), (...) datetime.datetime(1997, 9, 3, 16, 20), datetime.datetime(1997, 9, 3, 16, 40)]
An example where the days generated makes a difference because ofwkst.
>>> list(rrule(WEEKLY, interval=2, count=4, byweekday=(TU,SU), wkst=MO, dtstart=parse("19970805T090000")))[datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 10, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 24, 9, 0)]>>> list(rrule(WEEKLY, interval=2, count=4, byweekday=(TU,SU), wkst=SU, dtstart=parse("19970805T090000")))[datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 17, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 31, 9, 0)]
Therruleset type allows more complex recurrence setups, mixingmultiple rules, dates, exclusion rules, and exclusion dates.The type constructor takes the following keyword arguments:
The following methods are available:
Include the givenrrule instance in the recurrence setgeneration.
Include the givendatetime instance in the recurrenceset generation.
Include the givenrrule instance in the recurrence setexclusion list. Dates which are part of the given recurrencerules will not be generated, even if some inclusiverruleorrdate matches them.
Include the givendatetime instance in the recurrence setexclusion list. Dates included that way will not be generated,even if some inclusiverrule orrdate matches them.
Returns the last recurrence before the givendatetimeinstance. Theinc keyword defines what happens ifdtis an occurrence. Withinc == True,ifdt itself is an occurrence, it will be returned.
Returns the first recurrence after the givendatetimeinstance. Theinc keyword defines what happens ifdtis an occurrence. Withinc == True,ifdt itself is an occurrence, it will be returned.
Returns all the occurrences of the rrule betweenafterandbefore. Theinc keyword defines what happensifafter and/orbefore are themselves occurrences.Withinc == True, they will be included in the list,if they are found in the recurrence set.
Besides these methods,rruleset instances also supportthe__getitem__() and__contains__() special methods,meaning that these are valid expressions:
set = rruleset(...)if datetime(...) in set: ...print set[0]print set[-1]print set[1:2]print set[::-2]
The getitem/slicing mechanism is smart enough to avoid getting the wholerecurrence set, if possible.
Daily, for 7 days, jumping Saturday and Sunday occurrences.
>>> set = rruleset()>>> set.rrule(rrule(DAILY, count=7, dtstart=parse("19970902T090000")))>>> set.exrule(rrule(YEARLY, byweekday=(SA,SU), dtstart=parse("19970902T090000")))>>> list(set)[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 8, 9, 0)]
Weekly, for 4 weeks, plus one time on day 7, and not on day 16.
>>> set = rruleset()>>> set.rrule(rrule(WEEKLY, count=4, dtstart=parse("19970902T090000")))>>> set.rdate(datetime.datetime(1997, 9, 7, 9, 0))>>> set.exdate(datetime.datetime(1997, 9, 16, 9, 0))>>> list(set)[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 23, 9, 0)]
Therrulestr() function is a parser forRFC-like syntaxes.The function prototype is:
rrulestr(str)
The string passed as parameter may be a multiple line string, asingle line string, or just theRRULE property value.
Additionally, it accepts the following keyword arguments:
IfTrue, therruleset orrrule created instancewill cache its results. Default is not to cache.
If given, it must be adatetime instance that will be usedwhen noDTSTART property is found in the parsed string. Ifit is not given, and the property is not found,datetime.now()will be used instead.
If set toTrue, lines will be unfolded following the RFCspecification. It defaults toFalse, meaning that spacesbefore every line will be stripped.
If set toTrue arruleset instance will be returned,even if only a single rule is found. The default is to return anrrule if possible, and anrruleset if necessary.
If set toTrue, the parser will operate in RFC-compatiblemode. Right now it means thatunfold will be turned on,and if aDTSTART is found, it will be considered the firstrecurrence instance, as documented in the RFC.
If set toTrue, the date parser will ignore timezoneinformation available in theDTSTART property, or theUNTIL attribute.
Every 10 days, 5 occurrences.
>>> list(rrulestr("""... DTSTART:19970902T090000... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5... """))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)]
Same thing, but passing only theRRULE value.
>>> list(rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", dtstart=parse("19970902T090000")))[datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)]
Notice that when using a single rule, it returns anrrule instance, unlessforceset was used.
>>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5")<dateutil.rrule.rrule instance at 0x30269f08>>>> rrulestr("""... DTSTART:19970902T090000... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5... """)<dateutil.rrule.rrule instance at 0x302699e0>>>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", forceset=True)<dateutil.rrule.rruleset instance at 0x30269f08>
But when anrruleset is needed, it is automatically used.
>>> rrulestr("""... DTSTART:19970902T090000... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5... RRULE:FREQ=DAILY;INTERVAL=5;COUNT=3... """)<dateutil.rrule.rruleset instance at 0x302699e0>
This module offers a generic date/time string parser which isable to parse most known formats to represent a date and/ortime.
That's probably the only function you'll need from this module.It offers you an interface to access the parser functionality andextract adatetime type out of a string.
The prototype of this function is:
parse(timestr)
Additionally, the following keyword arguments are available:
If given, this must be adatetime instance. Any fieldsmissing in the parsed date will be copied from this instance.The default value is the current date, at 00:00:00am.
False). Ifdayfirst is False, theMM-DD-YYYYformat will have precedence overDD-MM-YYYY in anambiguous date.
to False). Ifyearfirst is false, theMM-DD-YYformat will have precedence overYY-MM-DD in anambiguous date.
Iffuzzy is set to True, unknown tokens in the stringwill be ignored.
Whenever an ambiguous date is found, thedayfirst andyearfirst parameters will control how the informationis processed. Here is the precedence in each case:
Ifdayfirst isFalse andyearfirst isFalse,(default, if no parameter is given):
MM-DD-YY
DD-MM-YY
YY-MM-DD
Ifdayfirst isTrue andyearfirst isFalse:
DD-MM-YY
MM-DD-YY
YY-MM-DD
Ifdayfirst isFalse andyearfirst isTrue:
YY-MM-DD
MM-DD-YY
DD-MM-YY
Ifdayfirst isTrue andyearfirst isTrue:
YY-MM-DD
DD-MM-YY
MM-DD-YY
When a two digit year is found, it is processed consideringthe current year, so that the computed year is never morethan 49 years after then current year, nor 50 years before thecurrent year. In other words, if we are in year 2003, and theyear 30 is found, it will be considered as 2030, but if theyear 60 is found, it will be considered 1960.
The following code will prepare the environment:
>>> from dateutil.parser import *>>> from dateutil.tz import *>>> from datetime import *>>> TZOFFSETS = {"BRST": -10800}>>> BRSTTZ = tzoffset(-10800, "BRST")>>> DEFAULT = datetime(2003, 9, 25)
Some simple examples based on thedate command, using theTZOFFSET dictionary to provide the BRST timezone offset.
>>> parse("Thu Sep 25 10:36:28 BRST 2003", tzinfos=TZOFFSETS)datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))>>> parse("2003 10:36:28 BRST 25 Sep Thu", tzinfos=TZOFFSETS)datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))
Notice that since BRST is my local timezone, parsing it withoutfurther timezone settings will yield atzlocal timezone.
>>> parse("Thu Sep 25 10:36:28 BRST 2003")datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzlocal())
We can also ask to ignore the timezone explicitly:
>>> parse("Thu Sep 25 10:36:28 BRST 2003", ignoretz=True)datetime.datetime(2003, 9, 25, 10, 36, 28)
That's the same as processing a string without timezone:
>>> parse("Thu Sep 25 10:36:28 2003")datetime.datetime(2003, 9, 25, 10, 36, 28)
Without the year, but passing ourDEFAULT datetime to returnthe same year, no mattering what year we currently are in:
>>> parse("Thu Sep 25 10:36:28", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36, 28)
Strip it further:
>>> parse("Thu Sep 10:36:28", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36, 28)>>> parse("Thu 10:36:28", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36, 28)>>> parse("Thu 10:36", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36)>>> parse("10:36", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36)>>>
Strip in a different way:
>>> parse("Thu Sep 25 2003")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("Sep 25 2003")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("Sep 2003", default=DEFAULT)datetime.datetime(2003, 9, 25, 0, 0)>>> parse("Sep", default=DEFAULT)datetime.datetime(2003, 9, 25, 0, 0)>>> parse("2003", default=DEFAULT)datetime.datetime(2003, 9, 25, 0, 0)
Another format, based ondate -R (RFC822):
>>> parse("Thu, 25 Sep 2003 10:49:41 -0300")datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800))
ISO format:
>>> parse("2003-09-25T10:49:41.5-03:00")datetime.datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=tzoffset(None, -10800))
Some variations:
>>> parse("2003-09-25T10:49:41")datetime.datetime(2003, 9, 25, 10, 49, 41)>>> parse("2003-09-25T10:49")datetime.datetime(2003, 9, 25, 10, 49)>>> parse("2003-09-25T10")datetime.datetime(2003, 9, 25, 10, 0)>>> parse("2003-09-25")datetime.datetime(2003, 9, 25, 0, 0)
ISO format, without separators:
>>> parse("20030925T104941.5-0300")datetime.datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=tzinfo=tzoffset(None, -10800))>>> parse("20030925T104941-0300")datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800))>>> parse("20030925T104941")datetime.datetime(2003, 9, 25, 10, 49, 41)>>> parse("20030925T1049")datetime.datetime(2003, 9, 25, 10, 49)>>> parse("20030925T10")datetime.datetime(2003, 9, 25, 10, 0)>>> parse("20030925")datetime.datetime(2003, 9, 25, 0, 0)
Everything together.
>>> parse("199709020900")datetime.datetime(1997, 9, 2, 9, 0)>>> parse("19970902090059")datetime.datetime(1997, 9, 2, 9, 0, 59)
Different date orderings:
>>> parse("2003-09-25")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("2003-Sep-25")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("25-Sep-2003")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("Sep-25-2003")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("09-25-2003")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("25-09-2003")datetime.datetime(2003, 9, 25, 0, 0)
Check some ambiguous dates:
>>> parse("10-09-2003")datetime.datetime(2003, 10, 9, 0, 0)>>> parse("10-09-2003", dayfirst=True)datetime.datetime(2003, 9, 10, 0, 0)>>> parse("10-09-03")datetime.datetime(2003, 10, 9, 0, 0)>>> parse("10-09-03", yearfirst=True)datetime.datetime(2010, 9, 3, 0, 0)
Other date separators are allowed:
>>> parse("2003.Sep.25")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("2003/09/25")datetime.datetime(2003, 9, 25, 0, 0)
Even with spaces:
>>> parse("2003 Sep 25")datetime.datetime(2003, 9, 25, 0, 0)>>> parse("2003 09 25")datetime.datetime(2003, 9, 25, 0, 0)
Hours with letters work:
>>> parse("10h36m28.5s", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 36, 28, 500000)>>> parse("01s02h03m", default=DEFAULT)datetime.datetime(2003, 9, 25, 2, 3, 1)>>> parse("01h02m03", default=DEFAULT)datetime.datetime(2003, 9, 3, 1, 2)>>> parse("01h02", default=DEFAULT)datetime.datetime(2003, 9, 2, 1, 0)>>> parse("01h02s", default=DEFAULT)datetime.datetime(2003, 9, 25, 1, 0, 2)
With AM/PM:
>>> parse("10h am", default=DEFAULT)datetime.datetime(2003, 9, 25, 10, 0)>>> parse("10pm", default=DEFAULT)datetime.datetime(2003, 9, 25, 22, 0)>>> parse("12:00am", default=DEFAULT)datetime.datetime(2003, 9, 25, 0, 0)>>> parse("12pm", default=DEFAULT)datetime.datetime(2003, 9, 25, 12, 0)
Some special treating forpertain relations:
>>> parse("Sep 03", default=DEFAULT)datetime.datetime(2003, 9, 3, 0, 0)>>> parse("Sep of 03", default=DEFAULT)datetime.datetime(2003, 9, 25, 0, 0)
Fuzzy parsing:
>>> s = "Today is 25 of September of 2003, exactly " \... "at 10:49:41 with timezone -03:00.">>> parse(s, fuzzy=True)datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800))
Other random formats:
>>> parse("Wed, July 10, '96")datetime.datetime(1996, 7, 10, 0, 0)>>> parse("1996.07.10 AD at 15:08:56 PDT", ignoretz=True)datetime.datetime(1996, 7, 10, 15, 8, 56)>>> parse("Tuesday, April 12, 1952 AD 3:30:42pm PST", ignoretz=True)datetime.datetime(1952, 4, 12, 15, 30, 42)>>> parse("November 5, 1994, 8:15:30 am EST", ignoretz=True)datetime.datetime(1994, 11, 5, 8, 15, 30)>>> parse("3rd of May 2001")datetime.datetime(2001, 5, 3, 0, 0)>>> parse("5:50 A.M. on June 13, 1990")datetime.datetime(1990, 6, 13, 5, 50)
This module offers a generic easter computing method forany given year, using Western, Orthodox or Julian algorithms.
This method was ported from the work done byGM Arts,on top of the algorithm byClaus Tondering,which was based in part on the algorithm of Ouding (1940),as quoted in "Explanatory Supplement to the AstronomicalAlmanac", P. Kenneth Seidelmann, editor.
This algorithm implements three different eastercalculation methods:
These methods are represented by the constants:
EASTER_JULIAN = 1EASTER_ORTHODOX = 2EASTER_WESTERN = 3
The default method is method 3.
This module offers timezone implementations subclassingthe abstractdatetime.tzinfo type. There areclasses to handletzfileformat files (usually are in /etc/localtime,/usr/share/zoneinfo, etc), TZ environment string (in allknown formats), given ranges (with help from relativedeltas), local machine timezone, fixed offset timezone,and UTC timezone.
This type implements a basic UTC timezone. The constructor of thistype accepts no parameters.
>>> from datetime import *>>> from dateutil.tz import *>>> datetime.now()datetime.datetime(2003, 9, 27, 9, 40, 1, 521290)>>> datetime.now(tzutc())datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc())>>> datetime.now(tzutc()).tzname()'UTC'
This type implements a fixed offset timezone, with nosupport to daylight saving times. Here is the prototype of thetype constructor:
tzoffset(name, offset)
Thename parameter may be optionally set toNone, andoffset must be given in seconds.
>>> from datetime import *>>> from dateutil.tz import *>>> datetime.now(tzoffset("BRST", -10800))datetime.datetime(2003, 9, 27, 9, 52, 43, 624904, tzinfo=tzinfo=tzoffset('BRST', -10800))>>> datetime.now(tzoffset("BRST", -10800)).tzname()'BRST'>>> datetime.now(tzoffset("BRST", -10800)).astimezone(tzutc())datetime.datetime(2003, 9, 27, 12, 53, 11, 446419, tzinfo=tzutc())
This type implements timezone settings as known by theoperating system. The constructor of this type accepts noparameters.
>>> from datetime import *>>> from dateutil.tz import *>>> datetime.now(tzlocal())datetime.datetime(2003, 9, 27, 10, 1, 43, 673605, tzinfo=tzlocal())>>> datetime.now(tzlocal()).tzname()'BRST'>>> datetime.now(tzlocal()).astimezone(tzoffset(None, 0))datetime.datetime(2003, 9, 27, 13, 3, 0, 11493, tzinfo=tzoffset(None, 0))
This type implements timezone settings extracted from astring in known TZ environment variable formats. Here is the prototypeof the constructor:
tzstr(str)
Here are examples of the recognized formats:
EST5EDT
EST5EDT,4,0,6,7200,10,0,26,7200,3600
EST5EDT,4,1,0,7200,10,-1,0,7200,3600
EST5EDT4,M4.1.0/02:00:00,M10-5-0/02:00
EST5EDT4,95/02:00:00,298/02:00
EST5EDT4,J96/02:00:00,J299/02:00
Notice that if daylight information is not present, but adaylight abbreviation was provided,tzstr will follow theconvention of using the first sunday of April to start daylightsaving, and the last sunday of October to end it. If start orend time is not present, 2AM will be used, and if the daylightoffset is not present, the standard offset plus one hour willbe used. This convention is the same as used in the GNU libc.
This also means that some of the above examples are exactlyequivalent, and all of these examples are equivalentin the year of 2003.
Here is the example mentioned in thetime module documentation.
>>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'>>> time.tzset()>>> time.strftime('%X %x %Z')'02:07:36 05/08/03 EDT'>>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'>>> time.tzset()>>> time.strftime('%X %x %Z')'16:08:12 05/08/03 AEST'
And here is an example showing the same information usingtzstr,without touching system settings.
>>> tz1 = tzstr('EST+05EDT,M4.1.0,M10.5.0')>>> tz2 = tzstr('AEST-10AEDT-11,M10.5.0,M3.5.0')>>> dt = datetime(2003, 5, 8, 2, 7, 36, tzinfo=tz1)>>> dt.strftime('%X %x %Z')'02:07:36 05/08/03 EDT'>>> dt.astimezone(tz2).strftime('%X %x %Z')'16:07:36 05/08/03 AEST'
Are these really equivalent?
>>> tzstr('EST5EDT') == tzstr('EST5EDT,4,1,0,7200,10,-1,0,7200,3600')True
Check the daylight limit.
>>> datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname()'EST'>>> datetime(2003, 4, 6, 2, 00, tzinfo=tz).tzname()'EDT'>>> datetime(2003, 10, 26, 0, 59, tzinfo=tz).tzname()'EDT'>>> datetime(2003, 10, 26, 1, 00, tzinfo=tz).tzname()'EST'
This type offers the same functionality as thetzstr type, butinstead of timezone strings, information is passed usingrelativedeltas which are applied to a datetime set to the firstday of the year. Here is the prototype of this type's constructor:
tzrange(stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None):
Offsets must be given in seconds. Information not provided will beset to the defaults, as explained in thetzstr section above.
>>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT")True>>> from dateutil.relativedelta import *>>> range1 = tzrange("EST", -18000, "EDT")>>> range2 = tzrange("EST", -18000, "EDT", -14400,... relativedelta(hours=+2, month=4, day=1, weekday=SU(+1)),... relativedelta(hours=+1, month=10, day=31, weekday=SU(-1)))>>> tzstr('EST5EDT') == range1 == range2True
Notice a minor detail in the last example: while the DST should endat 2AM, the delta will catch 1AM. That's because the daylight savingtime should end at 2AM standard time (the difference between STD andDST is 1h in the given example) instead of the DST time. That's howthetzinfo subtypes should deal with the extra hour that happenswhen going back to the standard time. Checktzinfo documentationfor more information.
This type allows one to use tzfile(5) format timezone files to extractcurrent and historical zone information. Here is the type constructorprototype:
tzfile(fileobj)
Wherefileobj is either a filename or a file-like object witharead() method.
>>> tz = tzfile("/etc/localtime")>>> datetime.now(tz)datetime.datetime(2003, 9, 27, 12, 3, 48, 392138, tzinfo=tzfile('/etc/localtime'))>>> datetime.now(tz).astimezone(tzutc())datetime.datetime(2003, 9, 27, 15, 3, 53, 70863, tzinfo=tzutc())>>> datetime.now(tz).tzname()'BRST'>>> datetime(2003, 1, 1, tzinfo=tz).tzname()'BRDT'
Check the daylight limit.
>>> tz = tzfile('/usr/share/zoneinfo/EST5EDT')>>> datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname()'EST'>>> datetime(2003, 4, 6, 2, 00, tzinfo=tz).tzname()'EDT'>>> datetime(2003, 10, 26, 0, 59, tzinfo=tz).tzname()'EDT'>>> datetime(2003, 10, 26, 1, 00, tzinfo=tz).tzname()'EST'
This type is able to parseiCalendarstyleVTIMEZONE sessions into a Python timezone object.The constuctor prototype is:
tzical(fileobj)
Wherefileobj is either a filename or a file-like object witharead() method.
tzid parameter. Otherwise, leaving it empty will yield the onlyavailable timezone.
Here is a sample file extracted from the RFC. This file definestheEST5EDT timezone, and will be used in the following example.
BEGIN:VTIMEZONETZID:US-EasternLAST-MODIFIED:19870101T000000ZTZURL:http://zones.stds_r_us.net/tz/US-EasternBEGIN:STANDARDDTSTART:19671029T020000RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10TZOFFSETFROM:-0400TZOFFSETTO:-0500TZNAME:ESTEND:STANDARDBEGIN:DAYLIGHTDTSTART:19870405T020000RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4TZOFFSETFROM:-0500TZOFFSETTO:-0400TZNAME:EDTEND:DAYLIGHTEND:VTIMEZONE
And here is an example exploring atzical type:
>>> from dateutil.tz import *; from datetime import *>>> tz = tzical('EST5EDT.ics')>>> tz.keys()['US-Eastern']>>> est = tz.get('US-Eastern')>>> est<tzicalvtz 'US-Eastern'>>>> datetime.now(est)datetime.datetime(2003, 10, 6, 19, 44, 18, 667987, tzinfo=<tzicalvtz 'US-Eastern'>)>>> est == tz.get()True
Let's check the daylight ranges, as usual:
>>> datetime(2003, 4, 6, 1, 59, tzinfo=est).tzname()'EST'>>> datetime(2003, 4, 6, 2, 00, tzinfo=est).tzname()'EDT'>>> datetime(2003, 10, 26, 0, 59, tzinfo=est).tzname()'EDT'>>> datetime(2003, 10, 26, 1, 00, tzinfo=est).tzname()'EST'
This type offers access to internal registry-based Windows timezones.The constuctor prototype is:
tzwin(name)
Wherename is the timezone name. There's a statictzwin.list()method to check the available names,
>>> tz = tzwin("E. South America Standard Time")
This type offers access to internal registry-based Windows timezones.The constructor accepts no parameters, so the prototype is:
tzwinlocal()
None if one is not available.
>>> tz = tzwinlocal()
This function is a helper that will try its best to get the righttimezone for your environment, or for the given string. The prototypeis as follows:
gettz(name=None)
If given, the parameter may be a filename, a path relative to the baseof the timezone information path (the base could be/usr/share/zoneinfo, for example), a string timezonespecification, or a timezone abbreviation. Ifname is not given,and theTZ environment variable is set, it's used instead. If theparameter is not given, andTZ is not set, the default tzfilepaths will be tried. Then, if no timezone information is found,an internal compiled database of timezones is used. When runningon Windows, the internal registry-based Windows timezones are alsoconsidered.
Example:
>>> from dateutil.tz import *>>> gettz()tzfile('/etc/localtime')>>> gettz("America/Sao Paulo")tzfile('/usr/share/zoneinfo/America/Sao_Paulo')>>> gettz("EST5EDT")tzfile('/usr/share/zoneinfo/EST5EDT')>>> gettz("EST5")tzstr('EST5')>>> gettz('BRST')tzlocal()>>> os.environ["TZ"] = "America/Sao Paulo">>> gettz()tzfile('/usr/share/zoneinfo/America/Sao_Paulo')>>> os.environ["TZ"] = "BRST">>> gettz()tzlocal()>>> gettz("Unavailable")>>>
This module provides direct access to the internal compileddatabase of timezones. The timezone data and the compiling toolsare obtained from the following project:
This function will try to retrieve the given timezone informationfrom the internal compiled database, and will cache its results.
Example:
>>> from dateutil import zoneinfo>>> zoneinfo.gettz("Brazil/East")tzfile('Brazil/East')
python-dateutil (last edited 2011-03-24 17:45:39 byGustavoNiemeyer)