pyoda_time.time_zones package

Subpackages

Module contents

class pyoda_time.time_zones.AmbiguousTimeResolver

Bases: Protocol

Chooses between two ZonedDateTime values that resolve to the same LocalDateTime.

This delegate is used by Resolvers.create_mapping_resolver when handling an ambiguous local time, due to clocks moving backward in a time zone transition (usually due to an autumnal daylight saving transition).

The returned value should be one of the two parameter values, based on the policy of the specific implementation. Alternatively, it can raise an AmbiguousTimeError to implement a policy of “reject ambiguous times.”

See the Resolvers class for predefined implementations.

Implementations of this delegate can reasonably assume that the target local date and time really is ambiguous; the behaviour when the local date and time can be unambiguously mapped into the target time zone (or when it’s skipped) is undefined.

__init__(*args, **kwargs)
final class pyoda_time.time_zones.DateTimeZoneCache

Bases: IDateTimeZoneProvider

Provides an implementation of IDateTimeZoneProvider that caches results from an IDateTimeZoneSource.

The process of loading or creating time zones may be an expensive operation. This class implements an unlimited-size non-expiring cache over a time zone source, and adapts an implementation of the IDateTimeZoneSource interface to an IDateTimeZoneProvider.

__init__(source: IDateTimeZoneSource) None

Creates a provider backed by the given IDateTimeZoneSource.

Note that the source will never be consulted for requests for the fixed-offset timezones “UTC” and “UTC+/-Offset” (a standard implementation will be returned instead). This is true even if these IDs are advertised by the source.

Parameters:

source – The IDateTimeZoneSource for this provider.

Raises:

InvalidTimeZoneSourceErrorsource violates its contract.

get_system_default() DateTimeZone

Gets the time zone from this provider that matches the system default time zone, if a matching time zone is available.

Callers should be aware that this method will throw DateTimeZoneNotFoundError if no matching time zone is found. For the built-in Pyoda Time providers, this is unlikely to occur in practice (assuming the system is using a standard Windows time zone), but can occur even then, if no mapping is found. The TZDB source contains mappings for almost all Windows system time zones, but a few (such as “Mid-Atlantic Standard Time”) are unmappable.

Returns:

The provider-specific representation of the system default time zone.

Raises:

DateTimeZoneNotFoundError – The system default time zone is not mapped by this provider.

get_zone_or_none(zone_id: str) DateTimeZone | None

Returns the time zone for the given ID, if it’s available.

Note that this may return a DateTimeZone that has a different ID to that requested, if the ID provided is an alias.

Note also that this method is not required to return the same DateTimeZone instance for successive requests for the same ID; however, all instances returned for a given ID must compare as equal.

The fixed-offset timezones with IDs “UTC” and “UTC+/-Offset” are always available.

Parameters:

zone_id – The time zone ID to find.

Returns:

The DateTimeZone for the given ID or null if the provider does not support the given ID.

property ids: Iterable[str]

Gets the list of valid time zone ids advertised by this provider.

This list will be sorted in ordinal lexicographic order. It cannot be modified by callers, and must not be modified by the provider either: client code can safely treat it as thread-safe and deeply immutable.

In addition to the list returned here, providers always support the fixed-offset timezones with IDs “UTC” and “UTC+/-Offset”. These may or may not be included explicitly in this list.

Returns:

The Iterable of string ids.

property version_id: str

Gets the version ID of this provider. This is simply the IDateTimeZoneSource.version_id returned by the underlying source.

Returns:

The version ID of this provider.

final exception pyoda_time.time_zones.DateTimeZoneNotFoundError

Bases: KeyError

Exception thrown when time zone is requested from an IDateTimeZoneProvider but the specified ID is invalid for that provider.

class pyoda_time.time_zones.IDateTimeZoneSource

Bases: Protocol

Provides the interface for objects that can retrieve time zone definitions given an ID.

The interface presumes that the available time zones are static; there is no mechanism for updating the list of available time zones. Any time zone ID that is returned in get_ids must be resolved by for_id for the life of the source.

Implementations need not cache time zones or the available time zone IDs. Caching is typically provided by DateTimeZoneCache, which most consumers should use instead of consuming IDateTimeZoneSource directly in order to get better performance.

It is expected that any exceptions thrown are implementation-specific; nothing is explicitly specified in the interface. Typically this would be unusual to the point that callers would not try to catch them; any implementation which may break in ways that are sensible to catch should advertise this clearly, so that clients will know to handle the exceptions appropriately. No wrapper exception type is provided by Pyoda Time to handle this situation, and code in Pyoda Time does not try to catch such exceptions.

__init__(*args, **kwargs)
for_id(id_: str) DateTimeZone

Returns the time zone definition associated with the given ID.

Note that this is permitted to return a DateTimeZone that has a different ID to that requested, if the ID provided is an alias.

Note also that this method is not required to return the same DateTimeZone instance for successive requests for the same ID; however, all instances returned for a given ID must compare as equal.

It is advised that sources should document their behaviour regarding any fixed-offset timezones (i.e. “UTC” and “UTC+/-Offset”) that are included in the list returned by get_ids. (These IDs will not be requested by DateTimeZoneCache, but any users calling into the source directly may care.)

he source need not attempt to cache time zones; caching is typically provided by DateTimeZoneCache.

Parameters:

id – The ID of the time zone to return. This must be one of the IDs returned by get_ids.

Returns:

The DateTimeZone for the given ID.

Raises:

ValueErrorid_ is not supported by this source.

get_ids() Iterable[str]

Returns an unordered enumeration of the IDs available from this source.

Every value in this enumeration must return a valid time zone from for_id for the life of the source. The enumeration may be empty, but must not be null, and must not contain any elements which are null. It should not contain duplicates: this is not enforced, and while it may not have a significant impact on clients in some cases, it is generally unfriendly. The built-in implementations never return duplicates.

The source is not required to provide the IDs in any particular order, although they should be distinct.

Note that this list may optionally contain any of the fixed-offset timezones (with IDs “UTC” and “UTC+/-Offset”), but there is no requirement they be included.

Returns:

The IDs available from this source.

get_system_default_id() str | None

Returns this source’s ID for the system default time zone.

Returns:

The ID for the system default time zone for this source, or None if the system default time zone has no mapping in this source.

property version_id: str

Returns an appropriate version ID for diagnostic purposes, which must not be null.

This doesn’t have any specific format; it’s solely for diagnostic purposes. The included sources return strings of the format “source identifier: source version” indicating where the information comes from and which version of the source information has been loaded.

Returns:

An appropriate version ID for diagnostic purposes.

exception pyoda_time.time_zones.InvalidDateTimeZoneSourceError

Bases: Exception

Exception thrown to indicate that a time zone source has violated the contract of IDateTimeZoneSource.

This exception is primarily intended to be thrown from DateTimeZoneCache, and only in the face of a buggy source; user code should not usually need to be aware of this or catch it.

class pyoda_time.time_zones.Resolvers

Bases: object

Commonly-used implementations of the delegates used in resolving a LocalDateTime to a ZonedDateTime, and a method to combine two “partial” resolvers into a full one.

This class contains predefined implementations of ZoneLocalMappingResolver, AmbiguousTimeResolver, and SkippedTimeResolver, along with CreateMappingResolver, which produces a ZoneLocalMappingResolver from instances of the other two.

class property lenient_resolver: ZoneLocalMappingResolver

A ZoneLocalMappingResolver which never raises an exception due to ambiguity or skipped time.

Ambiguity is handled by returning the earlier occurrence, and skipped times are shifted forward by the duration of the gap. This resolver combines return_earlier and return_forward_shifted.

Returns:

A ZoneLocalMappingResolver which never throws an exception due to ambiguity or skipped time.

class property strict_resolver: ZoneLocalMappingResolver

A ZoneLocalMappingResolver which only ever succeeds in the (usual) case where the result of the mapping is unambiguous.

If the mapping is ambiguous or skipped, this raises SkippedTimeError or AmbiguousTimeError as appropriate.

This resolver combines throw_when_ambiguous and throw_when_skipped.

Returns:

A ZoneLocalMappingResolver which only ever succeeds in the (usual) case where the result of the mapping is unambiguous.

class pyoda_time.time_zones.SkippedTimeResolver

Bases: Protocol

Resolves a LocalDateTime to a ZonedDateTime in the situation where the requested local time does not exist in the target time zone.

This delegate is used by Resolvers.create_mapping_resolver when handling the situation where the requested local time does not exist, due to clocks moving forward in a time zone transition (usually due to a spring daylight saving transition).

The returned value will necessarily represent a different local date and time to the target one, but the exact form of mapping is up to the delegate implementation. For example, it could return a value as close to the target local date and time as possible, or the time immediately after the transition. Alternatively, it can throw a SkippedTimeError to implement a policy of “reject skipped times.”

See the Resolvers class for predefined implementations.

Implementations of this delegate can reasonably assume that the target local date and time really is skipped; the behaviour when the local date and time can be directly mapped into the target time zone is undefined.

__init__(*args, **kwargs)
class pyoda_time.time_zones.TzdbZone1970Location

Bases: object

A location entry generated from the “zone1970.tab” file in a TZDB release.

This can be used to provide users with a choice of time zone, although it is not internationalized. This is equivalent to TzdbZoneLocation, except that multiple countries may be represented.

class Country

Bases: object

A country represented within an entry in the “zone1970.tab” file, with the English name mapped from the “iso3166.tab” file.

Equality is defined component-wise: two values are considered equal if their country names are equal to each other, and their country codes are equal to each other.

__eq__(other: object) bool

Compares countries for equality.

See the type documentation for a description of equality semantics.

Parameters:

other – The country to compare with this one.

Returns:

True if the given country has the same name and code as this one; False otherwise.

__init__(name: str, code: str) None

Constructs a new country from its name and ISO-3166 2-letter code.

Parameters:
  • name – Country name; must not be empty.

  • code – 2-letter code

property code: str

Gets the ISO-3166 2-letter country code for the country.

Returns:

The ISO-3166 2-letter country code for the country.

equals(other: Country) bool

Compares countries for equality.

See the type documentation for a description of equality semantics.

Parameters:

other – The country to compare with this one.

Returns:

True if the given country has the same name and code as this one; False otherwise.

property name: str

Gets the English name of the country.

Returns:

The English name of the country.

__init__(latitude_seconds: int, longitude_seconds: int, countries: Iterable[Country], zone_id: str, comment: str) None

Creates a new location.

This constructor is only public for the sake of testability. Non-test code should usually obtain locations from a TzdbDateTimeZoneSource.

Parameters:
  • latitude_seconds – Latitude of the location, in seconds.

  • longitude_seconds – Longitude of the location, in seconds.

  • countries – Countries associated with this location. Must not be null, must have at least one entry, and all entries must be non-null.

  • zone_id – Time zone identifier of the location. Must not be null.

  • comment – Optional comment. Must not be null, but may be empty.

Raises:

ValueError – If latitude_seconds or longitude_seconds are invalid.

property comment: str

Gets the comment (in English) for the mapping, if any.

This is usually used to differentiate between locations in the same country. This will return an empty string if no comment was provided in the original data.

Returns:

The comment (in English) for the mapping, if any.

property countries: Sequence[Country]

Gets the list of countries associated with this location.

The list is immutable, and will always contain at least one entry. The list is in the order specified in “zone1970.tab”, so the first entry is always the country containing the position indicated by the latitude and longitude, and is the most populous country in the list. No entry in this list is ever null.

Returns:

The list of countries associated with this location

property latitude: float

Gets the latitude in degrees; positive for North, negative for South.

The value will be in the range [-90, 90].

Returns:

The latitude in degrees; positive for North, negative for South.

property longitude: float

Gets the longitude in degrees; positive for East, negative for West.

The value will be in the range [-180, 180].

Returns:

The longitude in degrees; positive for East, negative for West.

property zone_id: str

The ID of the time zone for this location.

If this mapping was fetched from a TzdbDateTimeZoneSource, it will always be a valid ID within that source.

Returns:

The ID of the time zone for this location.

final class pyoda_time.time_zones.TzdbZoneLocation

Bases: object

A location entry generated from the “zone.tab” file in a TZDB release.

This can be used to provide users with a choice of time zone, although it is not internationalized.

__init__(latitude_seconds: int, longitude_seconds: int, country_name: str, country_code: str, zone_id: str, comment: str) None

Creates a new location.

This constructor is only public for the sake of testability. Non-test code should usually obtain locations from a TzdbDateTimeZoneSource.

Parameters:
  • latitude_seconds – Latitude of the location, in seconds.

  • longitude_seconds – Longitude of the location, in seconds.

  • country_name – English country name of the location, in degrees. Must not be null.

  • country_code – ISO-3166 country code of the location. Must not be null.

  • zone_id – Time zone identifier of the location. Must not be null.

  • comment – Optional comment. Must not be null, but may be empty.

Raises:

ValueError – If latitude_seconds or longitude_seconds are invalid.

property comment: str

Gets the comment (in English) for the mapping, if any.

This is usually used to differentiate between locations in the same country. This will return an empty string if no comment was provided in the original data.

Returns:

The comment (in English) for the mapping, if any.

property country_code: str

Gets the ISO-3166 2-letter country code for the country containing the location.

Returns:

The ISO-3166 2-letter country code for the country containing the location.

property country_name: str

Gets the English name of the country containing the location, which is never empty.

Returns:

The English name of the country containing the location.

property latitude: float

Gets the latitude in degrees; positive for North, negative for South.

The value will be in the range [-90, 90].

Returns:

The latitude in degrees; positive for North, negative for South.

property longitude: float

Gets the longitude in degrees; positive for East, negative for West.

The value will be in the range [-180, 180].

Returns:

The longitude in degrees; positive for East, negative for West.

property zone_id: str

The ID of the time zone for this location.

If this mapping was fetched from a TzdbDateTimeZoneSource, it will always be a valid ID within that source.

Returns:

The ID of the time zone for this location.

final class pyoda_time.time_zones.ZoneInterval

Bases: object

Represents a range of time for which a particular Offset applies.

Equality is defined component-wise in terms of all properties: the name, the start and end, and the offsets. There is no ordering defined between zone intervals.

__contains__(instant: Instant) bool

Determines whether this period contains the given Instant in its range.

__eq__(other: object) bool

Return self==value.

__init__(*, name: str, start: Instant | None = None, end: Instant | None = None, wall_offset: Offset, savings: Offset) None
property duration: Duration

The Duration of this zone interval.

property end: Instant

The last Instant (exclusive) that the Offset applies.

equals(other: ZoneInterval) bool
property has_end: bool

Returns True if this zone interval has a fixed end point, or False if it extends to the beginning of time.

property has_start: bool

Returns True if this zone interval has a fixed start point, or False if it extends to the beginning of time.

property iso_local_end: LocalDateTime

Gets the local end time of the interval, as a LocalDateTime in the ISO calendar.

property iso_local_start: LocalDateTime

Gets the local start time of the interval, as a LocalDateTime in the ISO calendar.

property name: str

The name of this offset period (e.g. PST or PDT).

property savings: Offset

The daylight savings value for this period.

property standard_offset: Offset

Gets the standard offset for this period.

This is the offset without any daylight savings contributions.

property start: Instant

The first Instant that the Offset applies.

property wall_offset: Offset

The offset from UTC for this period.

This includes any daylight savings value.

final class pyoda_time.time_zones.ZoneLocalMapping

Bases: object

The result of mapping a LocalDateTime within a time zone, i.e. finding out at what “global” time the “local” time occurred.

This class is used as the return type of DateTimeZone.map_local. It allows for finely-grained handling of the three possible results:

Unambiguous Mapping

The local time occurs exactly once in the target time zone.

Ambiguous Mapping

The local time occurs twice in the target time zone, due to the offset from UTC changing. This usually occurs for an autumnal daylight saving transition, where the clocks are put back by an hour. If the clocks change from 2am to 1am for example, then 1:30am occurs twice - once before the transition and once afterwards.

Impossible mapping

The local time does not occur at all in the target time zone, due to the offset from UTC changing. This usually occurs for a vernal (spring-time) daylight saving transition, where the clocks are put forward by an hour. If the clocks change from 1am to 2am for example, then 1:30am is skipped entirely.

__init__() None

Raise TypeError if the decorated class has no public constructor.

Raises:

TypeError – This class is not intended to be instantiated directly.

__new__() _Ttype

Raise TypeError if the decorated class has no public constructor.

Raises:

TypeError – This class is not intended to be instantiated directly.

property count: int

Gets the number of results within this mapping: the number of distinct ZonedDateTime values which map to the original LocalDateTime.

Returns:

The number of results within this mapping: the number of distinct values which map to the original local date and time.

property early_interval: ZoneInterval

Gets the earlier ZoneInterval within this mapping.

For unambiguous mappings, this is the same as late_interval; for ambiguous mappings, this is the interval during which the mapped local time first occurs; for impossible mappings, this is the interval before which the mapped local time occurs.

Returns:

The earlier zone interval within this mapping.

first() ZonedDateTime

Returns a ZonedDateTime which maps to the original LocalDateTime in the mapped DateTimeZone: either the single result if the mapping is unambiguous, or the earlier result if the local date/time occurs twice in the time zone due to a time zone offset change such as an autumnal daylight saving transition.

Raises:

SkippedTimeError – The local date/time was skipped in the time zone.

Returns:

The unambiguous result of mapping a local date/time in a time zone.

last() ZonedDateTime

Returns a ZonedDateTime which maps to the original LocalDateTime in the mapped DateTimeZone: either the single result if the mapping is unambiguous, or the later result if the local date/time occurs twice in the time zone due to a time zone offset change such as an autumnal daylight saving transition.

Raises:

SkippedTimeError – The local date/time was skipped in the time zone.

Returns:

The unambiguous result of mapping a local date/time in a time zone.

property late_interval: ZoneInterval

Gets the later ZoneInterval within this mapping.

For unambiguous mappings, this is the same as early_interval; for ambiguous mappings, this is the interval during which the mapped local time last occurs; for impossible mappings, this is the interval after which the mapped local time occurs.

Returns:

The earlier zone interval within this mapping.

property local_date_time: LocalDateTime

Gets the LocalDateTime which was mapped within the time zone.

Returns:

The local date and time which was mapped within the time zone.

single() ZonedDateTime

Returns the single ZonedDateTime which maps to the original LocalDateTime in the mapped DateTimeZone.

Raises:
Returns:

The unambiguous result of mapping the local date/time in the time zone.

property zone: DateTimeZone

Gets the DateTimeZone in which this mapping was performed.

Returns:

The time zone in which this mapping was performed.

class pyoda_time.time_zones.ZoneLocalMappingResolver

Bases: Protocol

Resolves the result of attempting to map a local date and time to a target time zone.

This delegate is consumed by LocalDateTime.in_zone and DateTimeZone.resolve_local(LocalDateTime, ZoneLocalMappingResolver), among others. It provides the strategy for converting a ZoneLocalMapping (the result of attempting to map a local date and time to a target time zone) to a ZonedDateTime.

See the Resolvers class for predefined implementations and a way of combining separate SkippedTimeResolver and AmbiguousTimeResolver values.

__init__(*args, **kwargs)