tz

This module offers timezone implementations subclassing the abstractdatetime.tzinfo type. There are classes to handle tzfile formatfiles (usually are in/etc/localtime,/usr/share/zoneinfo,etc), TZ environment string (in all known formats), given ranges (with helpfrom relative deltas), local machine timezone, fixed offset timezone, and UTCtimezone.

Objects

dateutil.tz.UTC

A convenience instance ofdateutil.tz.tzutc.

New in version 2.7.0.

Functions

dateutil.tz.gettz(name=None)

Retrieve a time zone object from a string representation

This function is intended to retrieve thetzinfo subclassthat best represents the time zone that would be used if a POSIXTZ variable were set to the same value.

If no argument or an empty string is passed togettz, local timeis returned:

>>>gettz()tzfile('/etc/localtime')

This function is also the preferred way to map IANA tz database keystotzfile objects:

>>>gettz('Pacific/Kiritimati')tzfile('/usr/share/zoneinfo/Pacific/Kiritimati')

On Windows, the standard is extended to include the Windows-specificzone names provided by the operating system:

>>>gettz('Egypt Standard Time')tzwin('Egypt Standard Time')

Passing a GNUTZ style string time zone specification returns atzstr object:

>>>gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')
Parameters:

name – A time zone name (IANA, or, on Windows, Windows keys), location ofatzfile(5) zoneinfo file orTZ variable style time zonespecifier. An empty string, no argument orNone is interpretedas local time.

Returns:

Returns an instance of one ofdateutil’stzinfosubclasses.

Changed in version 2.7.0:After version 2.7.0, any two calls togettz using the sameinput strings will return the same object:

>>>tz.gettz('America/Chicago')istz.gettz('America/Chicago')True

In addition to improving performance, this ensures that“same zone” semantics are used for datetimes in the same zone.

gettz.nocache()

A non-cached version of gettz

gettz.cache_clear()
dateutil.tz.enfold(dt,fold=1)[source]

Provides a unified interface for assigning thefold attribute todatetimes both before and after the implementation of PEP-495.

Parameters:

fold – The value for thefold attribute in the returned datetime. Thisshould be either 0 or 1.

Returns:

Returns an object for whichgetattr(dt,'fold',0) returnsfold for all versions of Python. In versions prior toPython 3.6, this is a_DatetimeWithFold object, which is asubclass ofdatetime.datetime with thefoldattribute added, iffold is 1.

New in version 2.6.0.

dateutil.tz.datetime_ambiguous(dt,tz=None)[source]

Given a datetime and a time zone, determine whether or not a given datetimeis ambiguous (i.e if there are two times differentiated only by their DSTstatus).

Parameters:
  • dt – Adatetime.datetime (whose time zone will be ignored iftzis provided.)

  • tz – Adatetime.tzinfo with support for thefold attribute. IfNone or not provided, the datetime’s own time zone will be used.

Returns:

Returns a boolean value whether or not the “wall time” is ambiguous intz.

New in version 2.6.0.

dateutil.tz.datetime_exists(dt,tz=None)[source]

Given a datetime and a time zone, determine whether or not a given datetimewould fall in a gap.

Parameters:
  • dt – Adatetime.datetime (whose time zone will be ignored iftzis provided.)

  • tz – Adatetime.tzinfo with support for thefold attribute. IfNone or not provided, the datetime’s own time zone will be used.

Returns:

Returns a boolean value whether or not the “wall time” exists intz.

New in version 2.7.0.

dateutil.tz.resolve_imaginary(dt)[source]

Given a datetime that may be imaginary, return an existing datetime.

This function assumes that an imaginary datetime represents what thewall time would be in a zone had the offset transition not occurred, soit will always fall forward by the transition’s change in offset.

>>>fromdateutilimporttz>>>fromdatetimeimportdatetime>>>NYC=tz.gettz('America/New_York')>>>print(tz.resolve_imaginary(datetime(2017,3,12,2,30,tzinfo=NYC)))2017-03-12 03:30:00-04:00>>>KIR=tz.gettz('Pacific/Kiritimati')>>>print(tz.resolve_imaginary(datetime(1995,1,1,12,30,tzinfo=KIR)))1995-01-02 12:30:00+14:00

As a note,datetime.astimezone() is guaranteed to produce a valid,existing datetime, so a round-trip to and from UTC is sufficient to getan extant datetime, however, this generally “falls back” to an earlier timerather than falling forward to the STD side (though no guarantees are madeabout this behavior).

Parameters:

dt – Adatetime.datetime which may or may not exist.

Returns:

Returns an existingdatetime.datetime. Ifdt was notimaginary, the datetime returned is guaranteed to be the same objectpassed to the function.

New in version 2.7.0.

Classes

classdateutil.tz.tzutc[source]

This is a tzinfo object that represents the UTC time zone.

Examples:

>>>fromdatetimeimport*>>>fromdateutil.tzimport*>>>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'

Changed in version 2.7.0:tzutc() is now a singleton, so the result oftzutc() willalways return the same object.

>>>fromdateutil.tzimporttzutc,UTC>>>tzutc()istzutc()True>>>tzutc()isUTCTrue
classdateutil.tz.tzoffset(name,offset)[source]

A simple class for representing a fixed offset from UTC.

Parameters:
  • name – The timezone name, to be returned whentzname() is called.

  • offset – The time zone offset in seconds, or (since version 2.6.0, representedas adatetime.timedelta object).

classdateutil.tz.tzlocal[source]

Atzinfo subclass built around thetime timezone functions.

classdateutil.tz.tzwinlocal[source]

Class representing the local time zone information in the Windows registry

Whiledateutil.tz.tzlocal makes system calls (via thetimemodule) to retrieve time zone information,tzwinlocal retrieves therules directly from the Windows registry and creates an object likedateutil.tz.tzwin.

Because Windows does not have an equivalent oftime.tzset(), onWindows,dateutil.tz.tzlocal instances will always reflect thetime zone settingsat the time that the process was started, meaningchanges to the machine’s time zone settings during the run of a programon Windows willnot be reflected bydateutil.tz.tzlocal.Becausetzwinlocal reads the registry directly, it is unaffected bythis issue.

Note

Only available on Windows

display()

Return the display name of the time zone.

transitions(year)

For a given year, get the DST on and off transition times, expressedalways on the standard time side. For zones with no transitions, thisfunction returnsNone.

Parameters:

year – The year whose transitions you would like to query.

Returns:

Returns atuple ofdatetime.datetime objects,(dston,dstoff) for zones with an annual DST transition, orNone for fixed offset zones.

classdateutil.tz.tzrange(stdabbr,stdoffset=None,dstabbr=None,dstoffset=None,start=None,end=None)[source]

Thetzrange object is a time zone specified by a set of offsets andabbreviations, equivalent to the way theTZ variable can be specifiedin POSIX-like systems, but using Python delta objects to specify DSTstart, end and offsets.

Parameters:
  • stdabbr – The abbreviation for standard time (e.g.'EST').

  • stdoffset

    An integer ordatetime.timedelta object or equivalentspecifying the base offset from UTC.

    If unspecified, +00:00 is used.

  • dstabbr

    The abbreviation for DST / “Summer” time (e.g.'EDT').

    If specified, with no other DST information, DST is assumed to occurand the default behavior ordstoffset,start andend isused. If unspecified and no other DST information is specified, itis assumed that this zone has no DST.

    If this is unspecified and other DST information isis specified,DST occurs in the zone but the time zone abbreviation is leftunchanged.

  • dstoffset – A an integer ordatetime.timedelta object or equivalentspecifying the UTC offset during DST. If unspecified and any other DSTinformation is specified, it is assumed to be the STD offset +1 hour.

  • start

    Arelativedelta.relativedelta object or equivalent specifyingthe time and time of year that daylight savings time starts. Tospecify, for example, that DST starts at 2AM on the 2nd Sunday inMarch, pass:

    relativedelta(hours=2,month=3,day=1,weekday=SU(+2))

    If unspecified and any other DST information is specified, the defaultvalue is 2 AM on the first Sunday in April.

  • end – Arelativedelta.relativedelta object or equivalentrepresenting the time and time of year that daylight savings timeends, with the same specification method as instart. One note isthat this should point to the first time in thestandard zone, so ifa transition occurs at 2AM in the DST zone and the clocks are set back1 hour to 1AM, set thehours parameter to +1.

Examples:

>>>tzstr('EST5EDT')==tzrange("EST",-18000,"EDT")True>>>fromdateutil.relativedeltaimport*>>>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
classdateutil.tz.tzstr(s,posix_offset=False)[source]

tzstr objects are time zone objects specified by a time-zone string asit would be passed to aTZ variable on POSIX-style systems (seetheGNU C Library: TZ Variable for more details).

There is one notable exception, which is that POSIX-style time zones use aninverted offset format, so normallyGMT+3 would be parsed as an offset3 hoursbehind GMT. Thetzstr time zone object will parse this as anoffset 3 hoursahead of GMT. If you would like to maintain the POSIXbehavior, pass aTrue value toposix_offset.

Thetzrange object provides the same functionality, but isspecified usingrelativedelta.relativedelta objects. rather thanstrings.

Parameters:
  • s – A time zone string inTZ variable format. This can be abytes (2.x:str),str (2.x:unicode) or a stream emitting unicode characters(e.g.StringIO).

  • posix_offset – Optional. If set toTrue, interpret strings such asGMT+3 orUTC+3 as being 3 hoursbehind UTC rather than ahead, per thePOSIX standard.

Caution

Prior to version 2.7.0, this function also supported time zonesin the format:

  • EST5EDT,4,0,6,7200,10,0,26,7200,3600

  • EST5EDT,4,1,0,7200,10,-1,0,7200,3600

This format is non-standard and has been deprecated; this functionwill raise aDeprecatedTZFormatWarning untilsupport is removed in a future version.

classdateutil.tz.tzical(fileobj)[source]

This object is designed to parse an iCalendar-styleVTIMEZONE structureas set out inRFC 5545 Section 4.6.5 into one or moretzinfo objects.

Parameters:

fileobj – A file or stream in iCalendar format, which should be UTF-8 encodedwith CRLF endings.

get(tzid=None)[source]

Retrieve adatetime.tzinfo object by itstzid.

Parameters:

tzid – If there is exactly one time zone available, omittingtzidor passingNone value returns it. Otherwise a validkey (which can be retrieved fromkeys()) is required.

Raises:

ValueError – Raised iftzid is not specified but there are either moreor fewer than 1 zone defined.

Returns:

Returns either adatetime.tzinfo object representingthe relevant time zone orNone if thetzid wasnot found.

keys()[source]

Retrieves the available time zones as a list.

classdateutil.tz.tzwin(name)[source]

Time zone object created from the zone info in the Windows registry

These are similar todateutil.tz.tzrange objects in thatthe time zone data is provided in the format of a single offset rulefor either 0 or 2 time zone transitions per year.

Param:

nameThe name of a Windows time zone key, e.g. “Eastern Standard Time”.The full list of keys can be retrieved withtzwin.list().

Note

Only available on Windows

display()

Return the display name of the time zone.

staticlist()

Return a list of all time zones known to the system.

transitions(year)

For a given year, get the DST on and off transition times, expressedalways on the standard time side. For zones with no transitions, thisfunction returnsNone.

Parameters:

year – The year whose transitions you would like to query.

Returns:

Returns atuple ofdatetime.datetime objects,(dston,dstoff) for zones with an annual DST transition, orNone for fixed offset zones.