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
DateorDateTimeobject to be compatible withdatetime.dateanddatetime.datetime.
- neo4j.time.MAX_YEAR: Final[int] = 9999¶
The largest year number allowed in a
DateorDateTimeobject to be compatible withdatetime.dateanddatetime.datetime.
Date¶
- class neo4j.time.Date(year, month, day)¶
Idealized date representation.
A
Dateobject represents a date (year, month, and day) in the proleptic Gregorian Calendar.Years between
0001and9999are 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 1and counts each subsequent day up to, and including, 31 Dec 9999. The standardyear,monthanddayvalue 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
Dateconstructor or by using theZeroDateconstant.
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
Datefrom 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
Datefrom a time stamp (seconds since unix epoch).
- classmethod Date.from_ordinal(ordinal)¶
Construct
Datefrom the proleptic Gregorian ordinal.0001-01-01has ordinal 1 and9999-12-31has ordinal 3,652,059. Values outside of this range trigger aValueError. 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.datevalue.
- classmethod Date.from_clock_time(clock_time, epoch)¶
Convert from a ClockTime relative to a given epoch.
- Parameters:
- Return type:
Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.
- classmethod Date.is_leap_year(year)¶
Indicate whether
yearis a leap year.- Parameters:
year (int) – the year to look up
- Raises:
ValueError – if
yearis 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
yearis 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_weekwill 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 Jancorresponding to1.
Operations¶
- Date.__hash__()¶
Return hash(self).
- Date.__eq__(other)¶
==comparison withDateordatetime.date.
- Date.__ne__(value, /)¶
Return self!=value.
- Date.__lt__(other)¶
<comparison withDateordatetime.date.
- Date.__gt__(other)¶
>comparison withDateordatetime.date.
- Date.__le__(other)¶
<=comparison withDateordatetime.date.
- Date.__ge__(other)¶
>=comparison withDateordatetime.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
Datewith 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
ClockTimerelative toepoch’s date.- Parameters:
epoch (Date | DateTime) – the epoch to which the date is relative
- Returns:
the
ClockTimevalue.- Return type:
ClockTime
Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.
- Date.to_native()¶
Convert to a native Python
datetime.datevalue.- 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.Dateinstance set to0000-00-00. This has an ordinal value of0.
Time¶
- class neo4j.time.Time(hour=0, minute=0, second=0, nanosecond=0, tzinfo=None)¶
Time of day.
The
Timeclass is a nanosecond-precision drop-in replacement for the standard librarydatetime.timeclass.A high degree of API compatibility with the standard library classes is provided.
neo4j.time.Timeobjects introduce the concept ofticks. This is simply a count of the number of nanoseconds since midnight, in many ways analogous to theneo4j.time.Dateordinal.ticksvalues are integers, with a minimum value of0and a maximum of86_399_999_999_999.Local times are represented by
Timewith 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
secondno longer acceptsfloatvalues.
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.timevalue.
- classmethod Time.from_clock_time(clock_time, epoch)¶
Convert from a
ClockTimerelative to a given epoch.This method, in contrast to most others of this package, assumes days of exactly 24 hours.
- Parameters:
- Return type:
Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.
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
floattodecimal.Decimalto mitigate rounding issues.Changed in version 5.0: The property’s type changed from
decimal.Decimaltoint. It does not longer cary sub-second information. Usenanosecondinstead.
- 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
Timeordatetime.time.
- Time.__ne__(value, /)¶
Return self!=value.
- Time.__lt__(other)¶
< comparison with
Timeordatetime.time.
- Time.__gt__(other)¶
> comparison with
Timeordatetime.time.
- Time.__le__(other)¶
<= comparison with
Timeordatetime.time.
Instance methods¶
- Time.replace(**kwargs)¶
Return a
Timewith 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.tzinfoorNone): 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 (
tzinfois None), else returnsself.tzinfo.utcoffset(self).- Raises:
ValueError – if
self.tzinfo.utcoffset(self)is not None and atimedeltawith 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
Noneor adatetime.timedelta.
- Return type:
timedelta | None
- Time.dst()¶
Get the daylight saving time adjustment (DST).
- Returns:
None if this is a local time (
tzinfois None), else returnsself.tzinfo.dst(self).- Raises:
ValueError – if
self.tzinfo.dst(self)is not None and atimedeltawith 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 adatetime.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.The returned
ClockTimeis relative toTime.min.Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.- Return type:
ClockTime
- Time.to_native()¶
Convert to a native Python
datetime.timevalue.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
DateTimeclass is a nanosecond-precision drop-in replacement for the standard librarydatetime.datetimeclass.As such, it contains both
DateandTimeinformation and draws functionality from those individual classes.A
DateTimeobject is fully compatible with the Python time zone library pytz. Functions such asnormalizeandlocalizecan be used in the same way as they are with the standard library classes.Regular construction of a
DateTimeobject requires at least theyear,monthanddayarguments to be supplied. The optionalhour,minuteandsecondarguments default to zero andtzinfodefaults toNone.year,month, anddayare passed to the constructor ofDate.hour,minute,second,nanosecond, andtzinfoare 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)¶
DateTimefrom 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)¶
DateTimefrom a time stamp (seconds since unix epoch).
- classmethod DateTime.from_ordinal(ordinal)¶
DateTimefrom an ordinal.For more info about ordinals see
Date.from_ordinal().
- classmethod DateTime.combine(date, time)¶
Combine a
Dateand aTimeto aDateTime.- Parameters:
- Raises:
AssertionError – if the parameter types don’t match.
- Return type:
- classmethod DateTime.from_native(dt)¶
Convert from a native Python
datetime.datetimevalue.
- classmethod DateTime.from_clock_time(clock_time, epoch)¶
Convert from a
ClockTimerelative to a given epoch.- Parameters:
- Raises:
ValueError – if
clock_timeis invalid.- Return type:
Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.
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
DateTimeanddatetime.datetime.
- DateTime.__ne__(value, /)¶
Return self!=value.
- DateTime.__lt__(other)¶
<comparison with another datetime.Accepts
DateTimeanddatetime.datetime.
- DateTime.__gt__(other)¶
>comparison with another datetime.Accepts
DateTimeanddatetime.datetime.
- DateTime.__le__(other)¶
<=comparison with another datetime.Accepts
DateTimeanddatetime.datetime.
- DateTime.__ge__(other)¶
>=comparison with another datetime.Accepts
DateTimeanddatetime.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
DateTimeyields the duration between the two as aDuration.Subtracting a
datetime.datetimeyields the duration between the two as adatetime.timedelta.Subtracting a
datetime.timedeltaor aDurationyields theDateTimethat’s the given duration away.
Instance methods¶
- DateTime.replace(**kwargs)¶
Return a
DateTimewith 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.The returned
ClockTimeis relative toDateTime.min.Deprecated since version 6.0:
ClockTimeis an implementation detail. It and its related methods will be removed in a future version.- Return type:
ClockTime
- DateTime.to_native()¶
Convert to a native Python
datetime.datetimevalue.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
DateTimeas ISO formatted string.This method joins
self.date().iso_format()(seeDate.iso_format()) andself.timetz().iso_format()(seeTime.iso_format()) withsepin 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
Durationrepresents the difference between two points in time. Duration objects store a composite value ofmonths,days,seconds, andnanoseconds. Unlikedatetime.timedeltahowever, days, and seconds/nanoseconds are never interchanged. All values except seconds and nanoseconds are applied separately in calculations (element-wise).A
Durationstores four primary instance attributes internally:months,days,secondsandnanoseconds. 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 conflictingsecondsandnanosecondssigns. This structure allows the modelling of durations such as3 months minus 2 days.To determine if a
Durationdis overflowing the accepted values of the database, first, allnanosecondsoutside the range -999_999_999 and 999_999_999 are transferred into the seconds field. Then,months,days, andsecondsare 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
monthsweeks (float) – will be added times 7 to
dayshours (float) – will be added times 3,600,000,000,000 to
nanosecondsminutes (float) – will be added times 60,000,000,000 to
nanosecondsseconds (float) – will be added times 1,000,000,000 to
nanosecondsmilliseconds (float) – will be added times 1,000,000 to
nanosecondsmicroseconds (float) – will be added times 1,000 to
nanosecondsnanoseconds (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
Durationordatetime.timedelta.
- Duration.__sub__(other)¶
Subtract a
Durationordatetime.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__().