tz.tz

This module offers timezone implementations subclassing the abstract datetime.tzinfo type. There are classes to handle tzfile format files (usually are in /etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in all known formats), given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, and UTC timezone.

Module Contents

Classes

tzutc() This is a tzinfo object that represents the UTC time zone.
tzoffset(self,name,offset) A simple class for representing a fixed offset from UTC.
tzlocal(self) A tzinfo subclass built around the time timezone functions.
_ttinfo(self)
_tzfile(self,**kwargs) Lightweight class for holding the relevant transition and time zone
tzfile(self,fileobj,filename=None) This is a tzinfo subclass thant allows one to use the tzfile(5)
tzrange(self,stdabbr,stdoffset=None,dstabbr=None,dstoffset=None,start=None,end=None) The tzrange object is a time zone specified by a set of offsets and
tzstr(self,s,posix_offset=False) tzstr objects are time zone objects specified by a time-zone string as
_tzicalvtzcomp(self,tzoffsetfrom,tzoffsetto,isdst,tzname=None,rrule=None)
_tzicalvtz(self,tzid,comps=list)
tzical(self,fileobj) This object is designed to parse an iCalendar-style VTIMEZONE structure
_ContextWrapper(self,context) Class for wrapping contexts so that they are passed through in a

Functions

__get_gettz()
datetime_exists(dt,tz=None) Given a datetime and a time zone, determine whether or not a given datetime
datetime_ambiguous(dt,tz=None) Given a datetime and a time zone, determine whether or not a given datetime
resolve_imaginary(dt) Given a datetime that may be imaginary, return an existing datetime.
_datetime_to_timestamp(dt) Convert a datetime.datetime object to an epoch timestamp in
class tzutc

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

Examples:

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

utcoffset(dt)
dst(dt)
tzname(dt)
is_ambiguous(dt)

Whether or not the “wall time” of a given datetime is ambiguous in this zone.

Parameters:dt – A datetime.datetime, naive or time zone aware.
Returns:Returns True if ambiguous, False otherwise.

New in version 2.6.0.

fromutc(dt)

Fast track version of fromutc() returns the original dt object for any valid datetime.datetime object.

__eq__(other)
__ne__(other)
__repr__()
class tzoffset(name, offset)

A simple class for representing a fixed offset from UTC.

Parameters:
  • name – The timezone name, to be returned when tzname() is called.
  • offset – The time zone offset in seconds, or (since version 2.6.0, represented as a datetime.timedelta object).
__init__(name, offset)
utcoffset(dt)
dst(dt)
tzname(dt)
fromutc(dt)
is_ambiguous(dt)

Whether or not the “wall time” of a given datetime is ambiguous in this zone.

Parameters:dt – A datetime.datetime, naive or time zone aware.
Returns:Returns True if ambiguous, False otherwise.

New in version 2.6.0.

__eq__(other)
__ne__(other)
__repr__()
class tzlocal

A tzinfo subclass built around the time timezone functions.

__init__()
utcoffset(dt)
dst(dt)
tzname(dt)
is_ambiguous(dt)

Whether or not the “wall time” of a given datetime is ambiguous in this zone.

Parameters:dt – A datetime.datetime, naive or time zone aware.
Returns:Returns True if ambiguous, False otherwise.

New in version 2.6.0.

_naive_is_dst(dt)
_isdst(dt, fold_naive=True)
__eq__(other)
__ne__(other)
__repr__()
class _ttinfo
__init__()
__repr__()
__eq__(other)
__ne__(other)
__getstate__()
__setstate__(state)
class _tzfile(**kwargs)

Lightweight class for holding the relevant transition and time zone information read from binary tzfiles.

__init__(**kwargs)
class tzfile(fileobj, filename=None)

This is a tzinfo subclass thant allows one to use the tzfile(5) format timezone files to extract current and historical zone information.

Parameters:
  • fileobj – This can be an opened file stream or a file name that the time zone information can be read from.
  • filename – This is an optional parameter specifying the source of the time zone information in the event that fileobj is a file object. If omitted and fileobj is a file stream, this parameter will be set either to fileobj’s name attribute or to repr(fileobj).

See Sources for Time Zone and Daylight Saving Time Data for more information. Time zone files can be compiled from the IANA Time Zone database files with the zic time zone compiler

Note

Only construct a tzfile directly if you have a specific timezone file on disk that you want to read into a Python tzinfo object. If you want to get a tzfile representing a specific IANA zone, (e.g. 'America/New_York'), you should call dateutil.tz.gettz() with the zone identifier.

Examples:

Using the US Eastern time zone as an example, we can see that a tzfile provides time zone information for the standard Daylight Saving offsets:

The tzfile structure contains a fully history of the time zone, so historical dates will also have the right offsets. For example, before the adoption of the UTC standards, New York used local solar mean time:

And during World War II, New York was on “Eastern War Time”, which was a state of permanent daylight saving time:

__init__(fileobj, filename=None)
_set_tzdata(tzobj)

Set the time zone data of this object from a _tzfile object

_read_tzfile(fileobj)
_find_last_transition(dt, in_utc=False)
_get_ttinfo(idx)
_find_ttinfo(dt)
fromutc(dt)

The tzfile implementation of datetime.tzinfo.fromutc().

Parameters:

dt – A datetime.datetime object.

Raises:
  • TypeError – Raised if dt is not a datetime.datetime object.
  • ValueError – Raised if this is called with a dt which does not have this tzinfo attached.
Returns:

Returns a datetime.datetime object representing the wall time in self’s time zone.

is_ambiguous(dt, idx=None)

Whether or not the “wall time” of a given datetime is ambiguous in this zone.

Parameters:dt – A datetime.datetime, naive or time zone aware.
Returns:Returns True if ambiguous, False otherwise.

New in version 2.6.0.

_resolve_ambiguous_time(dt)
utcoffset(dt)
dst(dt)
tzname(dt)
__eq__(other)
__ne__(other)
__repr__()
__reduce__()
__reduce_ex__(protocol)
class tzrange(stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None)

The tzrange object is a time zone specified by a set of offsets and abbreviations, equivalent to the way the TZ variable can be specified in POSIX-like systems, but using Python delta objects to specify DST start, end and offsets.

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

    An integer or datetime.timedelta object or equivalent specifying 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 occur and the default behavior or dstoffset, start and end is used. If unspecified and no other DST information is specified, it is assumed that this zone has no DST.

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

  • dstoffset – A an integer or datetime.timedelta object or equivalent specifying the UTC offset during DST. If unspecified and any other DST information is specified, it is assumed to be the STD offset +1 hour.
  • start

    A relativedelta.relativedelta object or equivalent specifying the time and time of year that daylight savings time starts. To specify, for example, that DST starts at 2AM on the 2nd Sunday in March, pass:

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

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

  • end – A relativedelta.relativedelta object or equivalent representing the time and time of year that daylight savings time ends, with the same specification method as in start. One note is that this should point to the first time in the standard zone, so if a transition occurs at 2AM in the DST zone and the clocks are set back 1 hour to 1AM, set the hours parameter to +1.

Examples:

__init__(stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None)
transitions(year)

For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns None.

Parameters:year – The year whose transitions you would like to query.
Returns:Returns a tuple of datetime.datetime objects, (dston, dstoff) for zones with an annual DST transition, or None for fixed offset zones.
__eq__(other)
_dst_base_offset()
class tzstr(s, posix_offset=False)

tzstr objects are time zone objects specified by a time-zone string as it would be passed to a TZ variable on POSIX-style systems (see the GNU C Library: TZ Variable for more details).

There is one notable exception, which is that POSIX-style time zones use an inverted offset format, so normally GMT+3 would be parsed as an offset 3 hours behind GMT. The tzstr time zone object will parse this as an offset 3 hours ahead of GMT. If you would like to maintain the POSIX behavior, pass a True value to posix_offset.

The tzrange object provides the same functionality, but is specified using relativedelta.relativedelta objects. rather than strings.

Parameters:
  • s – A time zone string in TZ variable format. This can be a bytes (2.x: str), str (2.x: unicode) or a stream emitting unicode characters (e.g. StringIO).
  • posix_offset – Optional. If set to True, interpret strings such as GMT+3 or UTC+3 as being 3 hours behind UTC rather than ahead, per the POSIX standard.

Caution

Prior to version 2.7.0, this function also supported time zones in 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 function will raise a DeprecatedTZFormatWarning until support is removed in a future version.

__init__(s, posix_offset=False)
_delta(x, isend=0)
__repr__()
class _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None)
__init__(tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None)
class _tzicalvtz(tzid, comps=list)
__init__(tzid, comps=list)
_find_comp(dt)
_find_compdt(comp, dt)
utcoffset(dt)
dst(dt)
tzname(dt)
__repr__()
class tzical(fileobj)

This object is designed to parse an iCalendar-style VTIMEZONE structure as set out in RFC 5545 Section 4.6.5 into one or more tzinfo objects.

Parameters:fileobj – A file or stream in iCalendar format, which should be UTF-8 encoded with CRLF endings.
__init__(fileobj)
keys()

Retrieves the available time zones as a list.

get(tzid=None)

Retrieve a datetime.tzinfo object by its tzid.

Parameters:tzid – If there is exactly one time zone available, omitting tzid or passing None value returns it. Otherwise a valid key (which can be retrieved from keys()) is required.
Raises:ValueError – Raised if tzid is not specified but there are either more or fewer than 1 zone defined.
Returns:Returns either a datetime.tzinfo object representing the relevant time zone or None if the tzid was not found.
_parse_offset(s)
_parse_rfc(s)
__repr__()
__get_gettz()
datetime_exists(dt, tz=None)

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

Parameters:
  • dt – A datetime.datetime (whose time zone will be ignored if tz is provided.)
  • tz – A datetime.tzinfo with support for the fold attribute. If None or not provided, the datetime’s own time zone will be used.
Returns:

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

New in version 2.7.0.

datetime_ambiguous(dt, tz=None)

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

Parameters:
  • dt – A datetime.datetime (whose time zone will be ignored if tz is provided.)
  • tz – A datetime.tzinfo with support for the fold attribute. If None 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 in tz.

New in version 2.6.0.

resolve_imaginary(dt)

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

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

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

Parameters:dt – A datetime.datetime which may or may not exist.
Returns:Returns an existing datetime.datetime. If dt was not imaginary, the datetime returned is guaranteed to be the same object passed to the function.

New in version 2.7.0.

_datetime_to_timestamp(dt)

Convert a datetime.datetime object to an epoch timestamp in seconds since January 1, 1970, ignoring the time zone.

class _ContextWrapper(context)

Class for wrapping contexts so that they are passed through in a with statement.

__init__(context)
__enter__()
__exit__(**kwargs)