Instant

final class whenever.Instant(arg: str | datetime, /)[source]

A moment in time, independent of any timezone or calendar.

This is the right type when you only care about when something happened, not the local date or time. It maps 1:1 to a UNIX timestamp.

>>> from whenever import Instant
>>> py311_release = Instant.from_utc(2022, 10, 24, hour=17)
Instant("2022-10-24 17:00:00Z")
>>> py311_release.add(hours=3).timestamp()
1666641600

Can also be constructed from an ISO 8601 string, a UNIX timestamp, or a standard library datetime:

>>> Instant("2022-10-24T17:00:00Z")
Instant("2022-10-24 17:00:00Z")

Convert to other types for local date/time information:

>>> py311_release.to_tz("US/Pacific")
ZonedDateTime("2022-10-24 10:00:00-07:00[US/Pacific]")

Note

Although the debug representation uses UTC, Instant does not have .year, .hour, or other calendar attributes—it is not a UTC datetime. See the FAQ.

classmethod from_py_datetime(d: datetime, /) _T

Create an instance from a datetime object.

Deprecated since version 0.10.0: Use the constructor instead (e.g. Instant(d), ZonedDateTime(d), etc.)

Note

The datetime is checked for validity, raising similar exceptions to the constructor. ValueError is raised if the datetime doesn’t have the correct tzinfo matching the class. For example, ZonedDateTime requires a ZoneInfo tzinfo.

Warning

No exceptions are raised if the datetime is ambiguous. Its fold attribute is used to disambiguate.

classmethod from_timestamp(i: int | float, /) Instant[source]

Create an Instant from a UNIX timestamp (in seconds).

The inverse of the timestamp() method.

classmethod from_timestamp_millis(i: int, /) Instant[source]

Create an Instant from a UNIX timestamp (in milliseconds).

The inverse of the timestamp_millis() method.

classmethod from_timestamp_nanos(i: int, /) Instant[source]

Create an Instant from a UNIX timestamp (in nanoseconds).

The inverse of the timestamp_nanos() method.

classmethod from_utc(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
*,
nanosecond: int = 0,
) Instant[source]

Create an Instant defined by a UTC date and time.

classmethod now() Instant[source]

Create an Instant from the current time.

>>> Instant.now()
Instant("2024-06-15 12:34:56.789123456Z")
classmethod parse(s: str, /, *, format: str) Instant[source]

Parse an instant from a custom pattern string.

The pattern must include an offset field (x/X) to unambiguously identify the instant. See Pattern format for details.

Tip

If your input string doesn’t include an offset, parse it with PlainDateTime.parse() first, then convert using assume_utc() or assume_tz().

>>> Instant.parse("2024-03-15 14:30Z", format="YYYY-MM-DD hh:mmXXX")
Instant("2024-03-15 14:30:00Z")
>>> Instant.parse("2024-03-15 14:30+05:30", format="YYYY-MM-DD hh:mmxxx")
Instant("2024-03-15 09:00:00Z")
classmethod parse_iso(s: str, /) Instant[source]

Parse an ISO 8601 string. Supports basic and extended formats, but not week dates or ordinal dates.

See the docs on ISO8601 support for more information.

The inverse of the format_iso() method.

classmethod parse_rfc2822(s: str, /) Instant[source]

Parse a UTC datetime in RFC 2822 format.

The inverse of the format_rfc2822() method.

>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 GMT")
Instant("2020-08-15 23:12:00Z")
>>> # also valid:
>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 +0000")
>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 +0800")
>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 -0000")
>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 UT")
>>> Instant.parse_rfc2822("Sat, 15 Aug 2020 23:12:00 MST")

Note

  • Although technically part of the RFC 2822 standard, comments within folding whitespace are not supported.

__add__(delta: TimeDelta) Instant[source]

Add a time amount to this datetime.

See the docs on arithmetic for more information.

__eq__(other: object) bool

Check if two datetimes represent at the same moment in time

a == b is equivalent to a.to_instant() == b.to_instant()

Note

If you want to exactly compare the values on their values instead, use exact_eq().

>>> Instant.from_utc(2020, 8, 15, hour=23) == Instant.from_utc(2020, 8, 15, hour=23)
True
>>> OffsetDateTime(2020, 8, 15, hour=23, offset=1) == (
...     ZonedDateTime(2020, 8, 15, hour=18, tz="America/New_York")
... )
True
__format__(spec: str, /) str[source]

Default object formatter.

Return str(self) if format_spec is empty. Raise TypeError otherwise.

__ge__(other: Instant | OffsetDateTime | ZonedDateTime) bool

Compare two datetimes by when they occur in time

a >= b is equivalent to a.to_instant() >= b.to_instant()

>>> OffsetDateTime(2020, 8, 15, hour=19, offset=-8) >= (
...     ZoneDateTime(2020, 8, 15, hour=20, tz="Europe/Amsterdam")
... )
True
__gt__(other: Instant | OffsetDateTime | ZonedDateTime) bool

Compare two datetimes by when they occur in time

a > b is equivalent to a.to_instant() > b.to_instant()

>>> OffsetDateTime(2020, 8, 15, hour=19, offset=-8) > (
...     ZoneDateTime(2020, 8, 15, hour=20, tz="Europe/Amsterdam")
... )
True
__le__(other: Instant | OffsetDateTime | ZonedDateTime) bool

Compare two datetimes by when they occur in time

a <= b is equivalent to a.to_instant() <= b.to_instant()

>>> OffsetDateTime(2020, 8, 15, hour=23, offset=8) <= (
...     ZoneDateTime(2020, 8, 15, hour=20, tz="Europe/Amsterdam")
... )
True
__lt__(other: Instant | OffsetDateTime | ZonedDateTime) bool

Compare two datetimes by when they occur in time

a < b is equivalent to a.to_instant() < b.to_instant()

>>> OffsetDateTime(2020, 8, 15, hour=23, offset=8) < (
...     ZoneDateTime(2020, 8, 15, hour=20, tz="Europe/Amsterdam")
... )
True
__str__() str

Return str(self).

__sub__(
other: Instant | OffsetDateTime | ZonedDateTime,
) TimeDelta[source]
__sub__(other: TimeDelta) Instant

Subtract another exact time or timedelta

See the docs on arithmetic for more information.

>>> d = Instant.from_utc(2020, 8, 15, hour=23, minute=12)
>>> d - hours(24) - seconds(5)
Instant("2020-08-14 23:11:55Z")
>>> d - Instant.from_utc(2020, 8, 14)
TimeDelta(47:12:00)
add(
*,
hours: float = 0,
minutes: float = 0,
seconds: float = 0,
milliseconds: float = 0,
microseconds: float = 0,
nanoseconds: int = 0,
) Instant[source]

Add a time amount to this instant.

See the docs on arithmetic for more information.

difference(
other: Instant | OffsetDateTime | ZonedDateTime,
/,
) TimeDelta

Calculate the difference between two instants in time.

Deprecated since version 0.10.0: Use the subtraction operator instead

exact_eq(other: _T, /) bool

Compare objects by their values (instead of whether they represent the same instant). Different types are never equal.

>>> a = OffsetDateTime(2020, 8, 15, hour=12, offset=1)
>>> b = OffsetDateTime(2020, 8, 15, hour=13, offset=2)
>>> a == b
True  # equivalent instants
>>> a.exact_eq(b)
False  # different values (hour and offset)
>>> a.exact_eq(Instant.now())
TypeError  # different types

Note

If a.exact_eq(b) is true, then a == b is also true, but the converse is not necessarily true.

format(pattern: str, /) str[source]

Format as a custom pattern string.

Instant formats as UTC; See Pattern format for details.

>>> Instant.from_utc(2024, 3, 15, 14, 30).format("YYYY-MM-DD hh:mm:ssXXX")
'2024-03-15 14:30:00Z'
format_iso(
*,
unit: Literal['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond', 'auto'] = 'auto',
basic: bool = False,
sep: Literal['T', ' '] = 'T',
) str[source]

Convert to the ISO 8601 string representation.

The inverse of the parse_iso() method.

format_rfc2822() str[source]

Format as an RFC 2822 string. The inverse of the parse_rfc2822() method.

>>> Instant.from_utc(2020, 8, 8, hour=23, minute=12).format_rfc2822()
"Sat, 08 Aug 2020 23:12:00 GMT"

Note

The output is also compatible with the (stricter) RFC 9110 standard.

py_datetime() datetime

Convert to a standard library datetime

Deprecated since version 0.10.0: Use to_stdlib() instead.

round(
unit: Literal['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond'] | TimeDelta = 'second',
/,
*,
increment: int = 1,
mode: RoundModeStr = 'half_even',
) Instant[source]

Round the instant to the specified unit and increment, or to a multiple of a TimeDelta. Various rounding modes are available.

>>> Instant.from_utc(2020, 1, 1, 12, 39, 59).round("minute", 15)
Instant("2020-01-01 12:45:00Z")
>>> Instant.from_utc(2020, 1, 1, 8, 9, 13).round("second", 5, mode="floor")
Instant("2020-01-01 08:09:10Z")
>>> Instant.from_utc(2020, 1, 1, 12, 39, 59).round(TimeDelta(minutes=15))
Instant("2020-01-01 12:45:00Z")
subtract(
*,
hours: float = 0,
minutes: float = 0,
seconds: float = 0,
milliseconds: float = 0,
microseconds: float = 0,
nanoseconds: int = 0,
) Instant[source]

Subtract a time amount from this instant.

See the docs on arithmetic for more information.

timestamp() int

The UNIX timestamp for this datetime. Inverse of from_timestamp().

>>> Instant.from_utc(1970, 1, 1).timestamp()
0
>>> ts = 1_123_000_000
>>> Instant.from_timestamp(ts).timestamp() == ts
True

Note

In contrast to the standard library, this method always returns an integer, not a float. This is because floating point timestamps are not precise enough to represent all instants to nanosecond precision. This decision is consistent with other modern date-time libraries.

timestamp_millis() int

Like timestamp(), but with millisecond precision.

timestamp_nanos() int

Like timestamp(), but with nanosecond precision.

to_fixed_offset(offset: int | TimeDelta = ..., /) OffsetDateTime

Convert to an OffsetDateTime that represents the same moment in time.

If not offset is given, the offset is taken from the original datetime.

to_stdlib() datetime

Convert to a standard library datetime

Note

  • Nanoseconds are truncated to microseconds. If you wish to customize the rounding behavior, use the round() method first.

  • For ZonedDateTime linked to a system timezone without a IANA timezone ID, the returned Python datetime will have a fixed offset (timezone tzinfo)

to_system_tz() ZonedDateTime

Convert to a ZonedDateTime of the system’s timezone.

to_tz(tz: str, /) ZonedDateTime

Convert to a ZonedDateTime that represents the same moment in time.

Raises:

TimeZoneNotFoundError – If the timezone ID is not found in the timezone database.

MAX: ClassVar[Instant] = Instant("9999-12-31 23:59:59.999999999Z")

The maximum representable instant.

MIN: ClassVar[Instant] = Instant("0001-01-01 00:00:00Z")

The minimum representable instant.