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 |
|
---|---|---|---|
Date |
|||
Time |
|
||
LocalTime |
|
||
DateTime |
|
||
LocalDateTime |
|
||
Duration |
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
orDateTime
object to be compatible withdatetime.date
anddatetime.datetime
.
- neo4j.time.MAX_YEAR: Final[int] = 9999¶
The largest year number allowed in a
Date
orDateTime
object to be compatible withdatetime.date
anddatetime.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:
A zero date can also be acquired by passing all zeroes to the
Date
constructor or by using theZeroDate
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:
- classmethod Date.from_timestamp(timestamp, tz=None)¶
Construct
Date
from a time stamp (seconds since unix epoch).- Parameters:
- 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:
- classmethod Date.utc_from_timestamp(timestamp)¶
Construct
Date
from a time stamp (seconds since unix epoch).
- 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 isto_ordinal()
. The ordinal 0 has a special semantic and will returnZeroDate
.- Raises:
ValueError – if the ordinal is outside the range [0, 3652059] (both values included).
- Parameters:
ordinal (int)
- Return type:
- 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:
- classmethod Date.from_native(d)¶
Convert from a native Python datetime.date value.
- classmethod Date.from_clock_time(clock_time, epoch)¶
Convert from a ClockTime relative to a given epoch.
- 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:
- 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:
Class attributes¶
Instance attributes¶
- 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 withDate
ordatetime.date
.
- Date.__ne__(other)¶
!=
comparison withDate
ordatetime.date
.
- Date.__lt__(other)¶
<
comparison withDate
ordatetime.date
.
- Date.__gt__(other)¶
>
comparison withDate
ordatetime.date
.
- Date.__le__(other)¶
<=
comparison withDate
ordatetime.date
.
- Date.__ge__(other)¶
>=
comparison withDate
ordatetime.date
.
- Date.__add__(other)¶
Add a
Duration
.- Raises:
ValueError – if the added duration has a time component.
- Parameters:
other (Duration)
- Return type:
Instance methods¶
- Date.replace(**kwargs)¶
Return a
Date
with one or more components replaced.- Keyword Arguments:
year (
typing.SupportsIndex
): overwrite the year - default: self.yearmonth (
typing.SupportsIndex
): overwrite the month - default: self.monthday (
typing.SupportsIndex
): overwrite the day - default: self.day
- Return type:
- Date.time_tuple()¶
Convert the date to
time.struct_time
.- Return type:
- 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:
- Date.to_clock_time(epoch)¶
Convert the date to
ClockTime
relative to epoch.
- Date.to_native()¶
Convert to a native Python
datetime.date
value.- Return type:
- 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 librarydatetime.time
class.A high degree of API compatibility with the standard library classes is provided.
neo4j.time.Time
objects introduce the concept ofticks
. This is simply a count of the number of nanoseconds since midnight, in many ways analogous to theneo4j.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 notzinfo
.- 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 acceptsfloat
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:
- classmethod Time.from_ticks(ticks, tz=None)¶
Create a time from ticks (nanoseconds since midnight).
- Parameters:
- Raises:
ValueError – if ticks is out of bounds (0 <= ticks < 86400000000000)
- Return type:
- classmethod Time.from_native(t)¶
Convert from a native Python
datetime.time
value.
- 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.
Class attributes¶
Instance attributes¶
- Time.ticks¶
The total number of nanoseconds since midnight.
- 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
todecimal.Decimal
to mitigate rounding issues.Changed in version 5.0: The property’s type changed from
decimal.Decimal
toint
. It does not longer cary sub-second information. Usenanosecond
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
ordatetime.time
.
- Time.__ne__(other)¶
!= comparison with
Time
ordatetime.time
.
- Time.__lt__(other)¶
< comparison with
Time
ordatetime.time
.
- Time.__gt__(other)¶
> comparison with
Time
ordatetime.time
.
- Time.__le__(other)¶
<= comparison with
Time
ordatetime.time
.
Instance methods¶
- Time.replace(**kwargs)¶
Return a
Time
with one or more components replaced.- Keyword Arguments:
hour (
typing.SupportsIndex
): overwrite the hour - default: self.hourminute (
typing.SupportsIndex
): overwrite the minute - default: self.minutesecond (
typing.SupportsIndex
): overwrite the second - default: int(self.second)nanosecond (
typing.SupportsIndex
): overwrite the nanosecond - default: self.nanosecondtzinfo (
datetime.tzinfo
or None): overwrite the timezone - default: self.tzinfo
- Return type:
- 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 adatetime.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.__format__(format_spec)¶
Default object formatter.
Return str(self) if format_spec is empty. Raise TypeError otherwise.
Special values¶
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 librarydatetime.datetime
class.As such, it contains both
Date
andTime
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 toNone
.year, month, and day are passed to the constructor of
Date
. hour, minute, second, nanosecond, and tzinfo are passed to the constructor ofTime
. 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
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:
- classmethod DateTime.from_timestamp(timestamp, tz=None)¶
DateTime
from a time stamp (seconds since unix epoch).- Parameters:
- 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:
- classmethod DateTime.utc_from_timestamp(timestamp)¶
DateTime
from a time stamp (seconds since unix epoch).Returns the DateTime as local date DateTime in UTC.
- classmethod DateTime.from_ordinal(ordinal)¶
DateTime
from an ordinal.For more info about ordinals see
Date.from_ordinal()
.
- classmethod DateTime.combine(date, time)¶
Combine a
Date
and aTime
to aDateTime
.- Parameters:
- Raises:
AssertionError – if the parameter types don’t match.
- Return type:
- classmethod DateTime.from_native(dt)¶
Convert from a native Python
datetime.datetime
value.
- classmethod DateTime.from_clock_time(clock_time, epoch)¶
Convert from a
ClockTime
relative to a given epoch.
Class attributes¶
- DateTime.min: Final[DateTime] = neo4j.time.DateTime(1, 1, 1, 0, 0, 0, 0)¶
The earliest date time value possible.
Instance attributes¶
- 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.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
.
Operations¶
- DateTime.__hash__()¶
Return hash(self).
- DateTime.__eq__(other)¶
==
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__ne__(other)¶
!=
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__lt__(other)¶
<
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__gt__(other)¶
>
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__le__(other)¶
<=
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__ge__(other)¶
>=
comparison with another datetime.Accepts
DateTime
anddatetime.datetime
.
- DateTime.__add__(other)¶
Add a
datetime.timedelta
.
- 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 aDuration
.Subtracting a
datetime.datetime
yields the duration between the two as adatetime.timedelta
.Subtracting a
datetime.timedelta
or aDuration
yields theDateTime
that’s the given duration away.
Instance methods¶
- DateTime.replace(**kwargs)¶
Return a
DateTime
with one or more components replaced.See
Date.replace()
andTime.replace()
for available arguments.- Return type:
- 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_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.weekday()¶
Get the weekday.
See
Date.weekday()
- Return type:
- DateTime.iso_weekday()¶
Get the ISO weekday.
- Return type:
- DateTime.iso_calendar()¶
Get date as ISO tuple.
- 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() (seeTime.iso_format()
) with sep in between.
- DateTime.__format__(format_spec)¶
Default object formatter.
Return str(self) if format_spec is empty. Raise TypeError otherwise.
Special values¶
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. Unlikedatetime.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
andnanoseconds
. These are maintained as individual values and are immutable. Each of these four attributes can carry its own sign, except fornanoseconds
, which always has the same sign asseconds
. The constructor will establish this state, should the duration be initialized with conflictingseconds
andnanoseconds
signs. This structure allows the modelling of durations such as3 months minus 2 days
.To determine if a
Duration
d
is overflowing the accepted values of the database, first, allnanoseconds
outside the range -999_999_999 and 999_999_999 are transferred into the seconds field. Then,months
,days
, andseconds
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
weeks (float) – will be added times 7 to 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:
Class attributes¶
Instance attributes¶
- 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.__add__(other)¶
Add a
Duration
ordatetime.timedelta
.
- Duration.__sub__(other)¶
Subtract a
Duration
ordatetime.timedelta
.
- Duration.__mul__(other)¶
-
The operation is performed element-wise on
(months, days, nanaoseconds)
whereyears 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).
- Duration.__truediv__(other)¶
-
The operation is performed element-wise on
(months, days, nanaoseconds)
whereyears 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).
- Duration.__floordiv__(other)¶
Integer division by an
int
.The operation is performed element-wise on
(months, days, nanaoseconds)
whereyears go into months,
weeks go into days,
seconds and all sub-second units go into nanoseconds.
Each element will be rounded towards -inf.
- Duration.__mod__(other)¶
Modulo operation by an
int
.The operation is performed element-wise on
(months, days, nanaoseconds)
whereyears go into months,
weeks go into days,
seconds and all sub-second units go into nanoseconds.
- Duration.__divmod__(other)¶
Division and modulo operation by an
int
.See
__floordiv__()
and__mod__()
.