Temporal Data Types

Temporal data types are implemented by the neo4j.time module.

It provides a set of types compliant with ISO-8601 and Cypher, which are similar to those found in the built-in datetime module. Sub-second values are measured to nanosecond precision and the types are compatible with pytz.

Warning

The temporal types were designed to be used with pytz. Other datetime.tzinfo implementations (e.g., datetime.timezone, zoneinfo, dateutil.tz) are not supported and are unlikely to work well.

The table below shows the general mappings between Cypher and the temporal types provided by the driver.

In addition, the built-in temporal types can be passed as parameters and will be mapped appropriately.

Cypher

Python driver type

Python built-in type

tzinfo

Date

neo4j.time.Date

datetime.date

Time

neo4j.time.Time

datetime.time

not None

LocalTime

neo4j.time.Time

datetime.time

None

DateTime

neo4j.time.DateTime

datetime.datetime

not None

LocalDateTime

neo4j.time.DateTime

datetime.datetime

None

Duration

neo4j.time.Duration

datetime.timedelta

Note

Cypher has built-in support for handling temporal values, and the underlying database supports storing these temporal values as properties on nodes and relationships, see https://neo4j.com/docs/cypher-manual/current/syntax/temporal/

Constants

neo4j.time.MIN_YEAR: Final[int] = 1

The smallest year number allowed in a Date or DateTime object to be compatible with datetime.date and datetime.datetime.

neo4j.time.MAX_YEAR: Final[int] = 9999

The largest year number allowed in a Date or DateTime object to be compatible with datetime.date and datetime.datetime.

Date

class neo4j.time.Date(year, month, day)

Idealized date representation.

A Date object represents a date (year, month, and day) in the proleptic Gregorian Calendar.

Years between 0001 and 9999 are supported, with additional support for the “zero date” used in some contexts.

Each date is based on a proleptic Gregorian ordinal, which models 1 Jan 0001 as day 1 and counts each subsequent day up to, and including, 31 Dec 9999. The standard year, month and day value of each date is also available.

Internally, the day of the month is always stored as-is, except for the last three days of that month. These are always stored as -1, -2 and -3 (counting from the last day). This system allows some temporal arithmetic (particularly adding or subtracting months) to produce a more desirable outcome than would otherwise be produced. Externally, the day number is always the same as would be written on a calendar.

Parameters:
Return type:

Date

A zero date can also be acquired by passing all zeroes to the Date constructor or by using the ZeroDate constant.

Class methods

classmethod Date.today(tz=None)

Get the current date.

Parameters:

tz (tzinfo | None) – timezone or None to get the local Date.

Raises:

OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038.

Return type:

Date

classmethod Date.utc_today()

Get the current date as UTC local date.

Return type:

Date

classmethod Date.from_timestamp(timestamp, tz=None)

Construct Date from a time stamp (seconds since unix epoch).

Parameters:
  • timestamp (float) – the unix timestamp (seconds since unix epoch).

  • tz (tzinfo | None) – timezone. Set to None to create a local Date.

Raises:

OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038.

Return type:

Date

classmethod Date.utc_from_timestamp(timestamp)

Construct Date from a time stamp (seconds since unix epoch).

Returns:

the Date as local date Date in UTC.

Parameters:

timestamp (float)

Return type:

Date

classmethod Date.from_ordinal(ordinal)

Construct Date from the proleptic Gregorian ordinal.

0001-01-01 has ordinal 1 and 9999-12-31 has ordinal 3,652,059. Values outside of this range trigger a ValueError. The corresponding instance method for the reverse date-to-ordinal transformation is to_ordinal(). The ordinal 0 has a special semantic and will return ZeroDate.

Raises:

ValueError – if the ordinal is outside the range [0, 3652059] (both values included).

Parameters:

ordinal (int)

Return type:

Date

classmethod Date.parse(s)

Parse a string to produce a Date.

Accepted formats:

‘Y-M-D’

Parameters:

s (str) – the string to be parsed.

Raises:

ValueError – if the string could not be parsed.

Return type:

Date

classmethod Date.from_native(d)

Convert from a native Python datetime.date value.

Parameters:

d (date) – the date to convert.

Return type:

Date

classmethod Date.from_clock_time(clock_time, epoch)

Convert from a ClockTime relative to a given epoch.

Parameters:
  • clock_time (ClockTime | tuple[float, int]) – the clock time as ClockTime or as tuple of (seconds, nanoseconds)

  • epoch (DateTime) – the epoch to which clock_time is relative

Return type:

Date

classmethod Date.is_leap_year(year)

Indicate whether year is a leap year.

Parameters:

year (int) – the year to look up

Raises:

ValueError – if year is out of range: MIN_YEAR <= year <= MAX_YEAR

Return type:

bool

classmethod Date.days_in_year(year)

Return the number of days in year.

Parameters:

year (int) – the year to look up

Raises:

ValueError – if year is out of range: MIN_YEAR <= year <= MAX_YEAR

Return type:

int

classmethod Date.days_in_month(year, month)

Return the number of days in month of year.

Parameters:
  • year (int) – the year to look up

  • month (int) – the month to look up

Raises:

ValueError – if year or month is out of range: MIN_YEAR <= year <= MAX_YEAR; 1 <= year <= 12

Return type:

int

Class attributes

Date.min: Final[Date] = neo4j.time.Date(1, 1, 1)

The earliest date value possible.

Date.max: Final[Date] = neo4j.time.Date(9999, 12, 31)

The latest date value possible.

Date.resolution: Final[Duration] = (0, 1, 0, 0)

The minimum resolution supported.

Instance attributes

Date.year

The year of the date.

Type:

int

Date.month

The month of the date.

Type:

int

Date.day

The day of the date.

Type:

int

Date.year_month_day

3-tuple of (year, month, day) describing the date.

Date.year_week_day

3-tuple of (year, week_of_year, day_of_week) describing the date.

day_of_week will be 1 for Monday and 7 for Sunday.

Date.year_day

2-tuple of (year, day_of_the_year) describing the date.

This is the number of the day relative to the start of the year, with 1 Jan corresponding to 1.

Operations

Date.__hash__()

Return hash(self).

Date.__eq__(other)

== comparison with Date or datetime.date.

Parameters:

other (object)

Return type:

bool

Date.__ne__(other)

!= comparison with Date or datetime.date.

Parameters:

other (object)

Return type:

bool

Date.__lt__(other)

< comparison with Date or datetime.date.

Parameters:

other (Date | date)

Return type:

bool

Date.__gt__(other)

> comparison with Date or datetime.date.

Parameters:

other (Date | date)

Return type:

bool

Date.__le__(other)

<= comparison with Date or datetime.date.

Parameters:

other (Date | date)

Return type:

bool

Date.__ge__(other)

>= comparison with Date or datetime.date.

Parameters:

other (Date | date)

Return type:

bool

Date.__add__(other)

Add a Duration.

Raises:

ValueError – if the added duration has a time component.

Parameters:

other (Duration)

Return type:

Date

Date.__sub__(other: Date | date) Duration
Date.__sub__(other: Duration) Date

Subtract a Date or Duration.

Returns:

If a Date is subtracted, the time between the two dates is returned as Duration. If a Duration is subtracted, a new Date is returned.

Return type:

Date or Duration

Raises:

ValueError – if the added duration has a time component.

Instance methods

Date.replace(**kwargs)

Return a Date with one or more components replaced.

Keyword Arguments:
Return type:

Date

Date.time_tuple()

Convert the date to time.struct_time.

Return type:

struct_time

Date.to_ordinal()

Get the date’s proleptic Gregorian ordinal.

The corresponding class method for the reverse ordinal-to-date transformation is Date.from_ordinal().

Return type:

int

Date.to_clock_time(epoch)

Convert the date to ClockTime relative to epoch.

Parameters:

epoch (Date | DateTime) – the epoch to which the date is relative

Return type:

ClockTime

Date.to_native()

Convert to a native Python datetime.date value.

Return type:

date

Date.weekday()

Get the day of the week where Monday is 0 and Sunday is 6.

Return type:

int

Date.iso_weekday()

Get the day of the week where Monday is 1 and Sunday is 7.

Return type:

int

Date.iso_calendar()

Return year_week_day.

Return type:

tuple[int, int, int]

Date.iso_format()

Return the Date as ISO formatted string.

Return type:

str

Date.__repr__()

Return repr(self).

Return type:

str

Date.__str__()

Return str(self).

Return type:

str

Date.__format__(format_spec)

Default object formatter.

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

Special values

neo4j.time.ZeroDate = neo4j.time.ZeroDate

A neo4j.time.Date instance set to 0000-00-00. This has an ordinal value of 0.

Time

class neo4j.time.Time(hour=0, minute=0, second=0, nanosecond=0, tzinfo=None)

Time of day.

The Time class is a nanosecond-precision drop-in replacement for the standard library datetime.time class.

A high degree of API compatibility with the standard library classes is provided.

neo4j.time.Time objects introduce the concept of ticks. This is simply a count of the number of nanoseconds since midnight, in many ways analogous to the neo4j.time.Date ordinal. ticks values are integers, with a minimum value of 0 and a maximum of 86_399_999_999_999.

Local times are represented by Time with no tzinfo.

Parameters:
  • hour (int) – the hour of the time. Must be in range 0 <= hour < 24.

  • minute (int) – the minute of the time. Must be in range 0 <= minute < 60.

  • second (int) – the second of the time. Must be in range 0 <= second < 60.

  • nanosecond (int) – the nanosecond of the time. Must be in range 0 <= nanosecond < 999999999.

  • tzinfo (_tzinfo | None) – timezone or None to get a local Time.

Raises:

ValueError – if one of the parameters is out of range.

Changed in version 5.0: The parameter second no longer accepts float values.

Class methods

classmethod Time.now(tz=None)

Get the current time.

Parameters:

tz (tzinfo | None) – optional timezone

Raises:

OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038.

Return type:

Time

classmethod Time.utc_now()

Get the current time as UTC local time.

Return type:

Time

classmethod Time.from_ticks(ticks, tz=None)

Create a time from ticks (nanoseconds since midnight).

Parameters:
  • ticks (int) – nanoseconds since midnight

  • tz (tzinfo | None) – optional timezone

Raises:

ValueError – if ticks is out of bounds (0 <= ticks < 86400000000000)

Return type:

Time

Changed in version 5.0: The parameter ticks no longer accepts float values but only int. It’s now nanoseconds since midnight instead of seconds.

classmethod Time.from_native(t)

Convert from a native Python datetime.time value.

Parameters:

t (time) – time to convert from

Return type:

Time

classmethod Time.from_clock_time(clock_time, epoch)

Convert from a ClockTime relative to a given epoch.

This method, in contrast to most others of this package, assumes days of exactly 24 hours.

Parameters:
  • clock_time (ClockTime | tuple[float, int]) – the clock time as ClockTime or as tuple of (seconds, nanoseconds)

  • epoch (DateTime) – the epoch to which clock_time is relative

Return type:

Time

Class attributes

Time.min: Final[Time] = neo4j.time.Time(0, 0, 0, 0)

The earliest time value possible.

Time.max: Final[Time] = neo4j.time.Time(23, 59, 59, 999999999)

The latest time value possible.

Time.resolution: Final[Duration] = (0, 0, 0, 1)

The minimum resolution supported.

Instance attributes

Time.ticks

The total number of nanoseconds since midnight.

Changed in version 5.0: The property’s type changed from float to int. It’s now nanoseconds since midnight instead of seconds.

Time.hour

The hours of the time.

Time.minute

The minutes of the time.

Time.second

The seconds of the time.

Changed in version 4.4: The property’s type changed from float to decimal.Decimal to mitigate rounding issues.

Changed in version 5.0: The property’s type changed from decimal.Decimal to int. It does not longer cary sub-second information. Use nanosecond instead.

Time.nanosecond

The nanoseconds of the time.

Time.hour_minute_second_nanosecond

The time as a tuple of (hour, minute, second, nanosecond).

Time.tzinfo

The timezone of this time.

Operations

Time.__hash__()

Return hash(self).

Time.__eq__(other)

== comparison with Time or datetime.time.

Parameters:

other (object)

Return type:

bool

Time.__ne__(other)

!= comparison with Time or datetime.time.

Parameters:

other (object)

Return type:

bool

Time.__lt__(other)

< comparison with Time or datetime.time.

Parameters:

other (Time | time)

Return type:

bool

Time.__gt__(other)

> comparison with Time or datetime.time.

Parameters:

other (Time | time)

Return type:

bool

Time.__le__(other)

<= comparison with Time or datetime.time.

Parameters:

other (Time | time)

Return type:

bool

Time.__ge__(other)

>= comparison with Time or datetime.time.

Parameters:

other (Time | time)

Return type:

bool

Instance methods

Time.replace(**kwargs)

Return a Time with one or more components replaced.

Keyword Arguments:
Return type:

Time

Time.utc_offset()

Return the UTC offset of this time.

Returns:

None if this is a local time (tzinfo is None), else returns self.tzinfo.utcoffset(self).

Raises:
  • ValueError – if self.tzinfo.utcoffset(self) is not None and a timedelta with a magnitude greater equal 1 day or that is not a whole number of minutes.

  • TypeError – if self.tzinfo.utcoffset(self) does return anything but None or a datetime.timedelta.

Return type:

timedelta | None

Time.dst()

Get the daylight saving time adjustment (DST).

Returns:

None if this is a local time (tzinfo is None), else returns self.tzinfo.dst(self).

Raises:
  • ValueError – if self.tzinfo.dst(self) is not None and a timedelta with a magnitude greater equal 1 day or that is not a whole number of minutes.

  • TypeError – if self.tzinfo.dst(self) does return anything but None or a datetime.timedelta.

Return type:

timedelta | None

Time.tzname()

Get the name of the Time’s timezone.

Returns:

None if the time is local (i.e., has no timezone), else return self.tzinfo.tzname(self)

Return type:

str | None

Time.to_clock_time()

Convert to ClockTime.

Return type:

ClockTime

Time.to_native()

Convert to a native Python datetime.time value.

This conversion is lossy as the native time implementation only supports a resolution of microseconds instead of nanoseconds.

Return type:

time

Time.iso_format()

Return the Time as ISO formatted string.

Return type:

str

Time.__repr__()

Return repr(self).

Return type:

str

Time.__str__()

Return str(self).

Return type:

str

Time.__format__(format_spec)

Default object formatter.

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

Special values

neo4j.time.Midnight: Final[Time] = neo4j.time.Time(0, 0, 0, 0)

A Time instance set to 00:00:00. This has a ticks value of 0.

neo4j.time.Midday: Final[Time] = neo4j.time.Time(12, 0, 0, 0)

A Time instance set to 12:00:00. This has a ticks value of 43200000000000.

DateTime

class neo4j.time.DateTime(year, month, day, hour=0, minute=0, second=0, nanosecond=0, tzinfo=None)

A point in time represented as a date and a time.

The DateTime class is a nanosecond-precision drop-in replacement for the standard library datetime.datetime class.

As such, it contains both Date and Time information and draws functionality from those individual classes.

A DateTime object is fully compatible with the Python time zone library pytz. Functions such as normalize and localize can be used in the same way as they are with the standard library classes.

Regular construction of a DateTime object requires at least the year, month and day arguments to be supplied. The optional hour, minute and second arguments default to zero and tzinfo defaults to None.

year, month, and day are passed to the constructor of Date. hour, minute, second, nanosecond, and tzinfo are passed to the constructor of Time. See their documentation for more details.

>>> dt = DateTime(2018, 4, 30, 12, 34, 56, 789123456); dt
neo4j.time.DateTime(2018, 4, 30, 12, 34, 56, 789123456)
>>> dt.second
56
Parameters:
  • year (int)

  • month (int)

  • day (int)

  • hour (int)

  • minute (int)

  • second (int)

  • nanosecond (int)

  • tzinfo (_tzinfo | None)

Return type:

DateTime

Class methods

classmethod DateTime.now(tz=None)

Get the current date and time.

Parameters:

tz (tzinfo | None) – timezone. Set to None to create a local DateTime.

Raises:

OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038.

Return type:

DateTime

classmethod DateTime.utc_now()

Get the current date and time in UTC.

Return type:

DateTime

classmethod DateTime.from_timestamp(timestamp, tz=None)

DateTime from a time stamp (seconds since unix epoch).

Parameters:
  • timestamp (float) – the unix timestamp (seconds since unix epoch).

  • tz (tzinfo | None) – timezone. Set to None to create a local DateTime.

Raises:

OverflowError – if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038.

Return type:

DateTime

classmethod DateTime.utc_from_timestamp(timestamp)

DateTime from a time stamp (seconds since unix epoch).

Returns the DateTime as local date DateTime in UTC.

Parameters:

timestamp (float)

Return type:

DateTime

classmethod DateTime.from_ordinal(ordinal)

DateTime from an ordinal.

For more info about ordinals see Date.from_ordinal().

Parameters:

ordinal (int)

Return type:

DateTime

classmethod DateTime.combine(date, time)

Combine a Date and a Time to a DateTime.

Parameters:
  • date (Date) – the date

  • time (Time) – the time

Raises:

AssertionError – if the parameter types don’t match.

Return type:

DateTime

classmethod DateTime.from_native(dt)

Convert from a native Python datetime.datetime value.

Parameters:

dt (datetime) – the datetime to convert

Return type:

DateTime

classmethod DateTime.from_clock_time(clock_time, epoch)

Convert from a ClockTime relative to a given epoch.

Parameters:
  • clock_time (ClockTime | tuple[float, int]) – the clock time as ClockTime or as tuple of (seconds, nanoseconds)

  • epoch (DateTime) – the epoch to which clock_time is relative

Raises:

ValueError – if clock_time is invalid.

Return type:

DateTime

Class attributes

DateTime.min: Final[DateTime] = neo4j.time.DateTime(1, 1, 1, 0, 0, 0, 0)

The earliest date time value possible.

DateTime.max: Final[DateTime] = neo4j.time.DateTime(9999, 12, 31, 23, 59, 59, 999999999)

The latest date time value possible.

DateTime.resolution: Final[Duration] = (0, 0, 0, 1)

The minimum resolution supported.

Instance attributes

DateTime.year

The year of the DateTime.

See Date.year.

DateTime.month

The year of the DateTime.

See Date.year.

DateTime.day

The day of the DateTime’s date.

See Date.day.

DateTime.year_month_day

The year_month_day of the DateTime’s date.

See Date.year_month_day.

DateTime.year_week_day

The year_week_day of the DateTime’s date.

See Date.year_week_day.

DateTime.year_day

The year_day of the DateTime’s date.

See Date.year_day.

DateTime.hour

The hour of the DateTime’s time.

See Time.hour.

DateTime.minute

The minute of the DateTime’s time.

See Time.minute.

DateTime.second

The second of the DateTime’s time.

See Time.second.

DateTime.nanosecond

The nanosecond of the DateTime’s time.

See Time.nanosecond.

DateTime.tzinfo

The tzinfo of the DateTime’s time.

See Time.tzinfo.

DateTime.hour_minute_second_nanosecond

The hour_minute_second_nanosecond of the DateTime’s time.

See Time.hour_minute_second_nanosecond.

Operations

DateTime.__hash__()

Return hash(self).

DateTime.__eq__(other)

== comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (object)

Return type:

bool

DateTime.__ne__(other)

!= comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (object)

Return type:

bool

DateTime.__lt__(other)

< comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (datetime | DateTime)

Return type:

bool

DateTime.__gt__(other)

> comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (object)

Return type:

bool

DateTime.__le__(other)

<= comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (datetime | DateTime)

Return type:

bool

DateTime.__ge__(other)

>= comparison with another datetime.

Accepts DateTime and datetime.datetime.

Parameters:

other (datetime | DateTime)

Return type:

bool

DateTime.__add__(other)

Add a datetime.timedelta.

Parameters:

other (timedelta | Duration)

Return type:

DateTime

DateTime.__sub__(other: DateTime) Duration
DateTime.__sub__(other: datetime) timedelta
DateTime.__sub__(other: Duration | timedelta) DateTime

Subtract a datetime/DateTime or a timedelta/Duration.

Subtracting a DateTime yields the duration between the two as a Duration.

Subtracting a datetime.datetime yields the duration between the two as a datetime.timedelta.

Subtracting a datetime.timedelta or a Duration yields the DateTime that’s the given duration away.

Instance methods

DateTime.date()

Get the date.

Return type:

Date

DateTime.time()

Get the time without timezone info.

Return type:

Time

DateTime.timetz()

Get the time with timezone info.

Return type:

Time

DateTime.replace(**kwargs)

Return a DateTime with one or more components replaced.

See Date.replace() and Time.replace() for available arguments.

Return type:

DateTime

DateTime.as_timezone(tz)

Convert this DateTime to another timezone.

Parameters:

tz (tzinfo) – the new timezone

Returns:

the same object if tz is :data:None. Else, a new DateTime that’s the same point in time but in a different timezone.

Return type:

DateTime

DateTime.utc_offset()

Get the date times utc offset.

See Time.utc_offset().

Return type:

timedelta | None

DateTime.dst()

Get the daylight saving time adjustment (DST).

See Time.dst().

Return type:

timedelta | None

DateTime.tzname()

Get the timezone name.

See Time.tzname().

Return type:

str | None

DateTime.to_ordinal()

Get the ordinal of the DateTime’s date.

See Date.to_ordinal()

Return type:

int

DateTime.to_clock_time()

Convert to ClockTime.

Return type:

ClockTime

DateTime.to_native()

Convert to a native Python datetime.datetime value.

This conversion is lossy as the native time implementation only supports a resolution of microseconds instead of nanoseconds.

Return type:

datetime

DateTime.weekday()

Get the weekday.

See Date.weekday()

Return type:

int

DateTime.iso_weekday()

Get the ISO weekday.

See Date.iso_weekday()

Return type:

int

DateTime.iso_calendar()

Get date as ISO tuple.

See Date.iso_calendar()

Return type:

tuple[int, int, int]

DateTime.iso_format(sep='T')

Return the DateTime as ISO formatted string.

This method joins self.date().iso_format() (see Date.iso_format()) and self.timetz().iso_format() (see Time.iso_format()) with sep in between.

Parameters:

sep (str) – the separator between the formatted date and time.

Return type:

str

DateTime.__repr__()

Return repr(self).

Return type:

str

DateTime.__str__()

Return str(self).

Return type:

str

DateTime.__format__(format_spec)

Default object formatter.

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

Special values

neo4j.time.Never = neo4j.time.DateTime(0, 0, 0, 0, 0, 0, 0)

A DateTime instance set to 0000-00-00T00:00:00. This has a Date component equal to ZeroDate and a

neo4j.time.UnixEpoch = neo4j.time.DateTime(1970, 1, 1, 0, 0, 0, 0)

A DateTime instance set to 1970-01-01T00:00:00.

Duration

class neo4j.time.Duration(years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, nanoseconds=0)

A difference between two points in time.

A Duration represents the difference between two points in time. Duration objects store a composite value of months, days, seconds, and nanoseconds. Unlike datetime.timedelta however, days, and seconds/nanoseconds are never interchanged. All values except seconds and nanoseconds are applied separately in calculations (element-wise).

A Duration stores four primary instance attributes internally: months, days, seconds and nanoseconds. These are maintained as individual values and are immutable. Each of these four attributes can carry its own sign, except for nanoseconds, which always has the same sign as seconds. The constructor will establish this state, should the duration be initialized with conflicting seconds and nanoseconds signs. This structure allows the modelling of durations such as 3 months minus 2 days.

To determine if a Duration d is overflowing the accepted values of the database, first, all nanoseconds outside the range -999_999_999 and 999_999_999 are transferred into the seconds field. Then, months, days, and seconds are summed up like so: months * 2629746 + days * 86400 + d.seconds + d.nanoseconds // 1000000000. (Like the integer division in Python, this one is to be understood as rounding down rather than towards 0.) This value must be between -(263) and (263 - 1) inclusive.

Parameters:
  • years (float) – will be added times 12 to months

  • months (float) – will be truncated to int (int(months))

  • weeks (float) – will be added times 7 to days

  • days (float) – will be truncated to int (int(days))

  • hours (float) – will be added times 3,600,000,000,000 to nanoseconds

  • minutes (float) – will be added times 60,000,000,000 to nanoseconds

  • seconds (float) – will be added times 1,000,000,000 to nanoseconds`

  • milliseconds (float) – will be added times 1,000,000 to nanoseconds

  • microseconds (float) – will be added times 1,000 to nanoseconds

  • nanoseconds (float) – will be truncated to int (int(nanoseconds))

Raises:

ValueError – the components exceed the limits as described above.

Return type:

Duration

Class attributes

Duration.min: Final[Duration] = (0, 0, -9223372036854775808, 0)

The lowest duration value possible.

Duration.max: Final[Duration] = (0, 0, 9223372036854775807, 999999999)

The highest duration value possible.

Instance attributes

Duration.months

The months of the Duration.

Duration.days

The days of the Duration.

Duration.seconds

The seconds of the Duration.

Duration.nanoseconds

The nanoseconds of the Duration.

Duration.years_months_days

Months and days components as a 3-tuple.

tuple of years, months and days.

Duration.hours_minutes_seconds_nanoseconds

Seconds and nanoseconds components as a 4-tuple.

tuple of hours, minutes, seconds and nanoseconds.

Operations

Duration.__bool__()

Falsy if all primary instance attributes are.

Return type:

bool

Duration.__add__(other)

Add a Duration or datetime.timedelta.

Parameters:

other (Duration | timedelta)

Return type:

Duration

Duration.__sub__(other)

Subtract a Duration or datetime.timedelta.

Parameters:

other (Duration | timedelta)

Return type:

Duration

Duration.__mul__(other)

Multiply by an int or float.

The operation is performed element-wise on (months, days, nanaoseconds) where

  • years go into months,

  • weeks go into days,

  • seconds and all sub-second units go into nanoseconds.

Each element will be rounded to the nearest integer (.5 towards even).

Parameters:

other (float)

Return type:

Duration

Duration.__truediv__(other)

Division by an int or float.

The operation is performed element-wise on (months, days, nanaoseconds) where

  • years go into months,

  • weeks go into days,

  • seconds and all sub-second units go into nanoseconds.

Each element will be rounded to the nearest integer (.5 towards even).

Parameters:

other (float)

Return type:

Duration

Duration.__floordiv__(other)

Integer division by an int.

The operation is performed element-wise on (months, days, nanaoseconds) where

  • years go into months,

  • weeks go into days,

  • seconds and all sub-second units go into nanoseconds.

Each element will be rounded towards -inf.

Parameters:

other (int)

Return type:

Duration

Duration.__mod__(other)

Modulo operation by an int.

The operation is performed element-wise on (months, days, nanaoseconds) where

  • years go into months,

  • weeks go into days,

  • seconds and all sub-second units go into nanoseconds.

Parameters:

other (int)

Return type:

Duration

Duration.__divmod__(other)

Division and modulo operation by an int.

See __floordiv__() and __mod__().

Parameters:

other (int)

Return type:

tuple[Duration, Duration]

Duration.__pos__()
Return type:

Duration

Duration.__neg__()
Return type:

Duration

Duration.__abs__()
Return type:

Duration

Duration.__repr__()

Return repr(self).

Return type:

str

Duration.__str__()

Return str(self).

Return type:

str

Instance methods

Duration.iso_format(sep='T')

Return the Duration as ISO formatted string.

Parameters:

sep (str) – the separator before the time components.

Return type:

str