|
| 1 | +"""Datetime function.""" |
| 2 | + |
| 3 | +from datetime import datetime, timezone |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from .function import Function |
| 7 | +from .function_metadata import FunctionDef |
| 8 | +from .temporal_utils import build_datetime_object, parse_temporal_arg |
| 9 | + |
| 10 | + |
| 11 | +@FunctionDef({ |
| 12 | + "description": ( |
| 13 | + "Returns a datetime value. With no arguments returns the current UTC datetime. " |
| 14 | + "Accepts an ISO 8601 string or a map of components (year, month, day, hour, minute, second, millisecond)." |
| 15 | + ), |
| 16 | + "category": "scalar", |
| 17 | + "parameters": [ |
| 18 | + { |
| 19 | + "name": "input", |
| 20 | + "description": "Optional. An ISO 8601 datetime string or a map of components.", |
| 21 | + "type": "string", |
| 22 | + "required": False, |
| 23 | + }, |
| 24 | + ], |
| 25 | + "output": { |
| 26 | + "description": ( |
| 27 | + "A datetime object with properties: year, month, day, hour, minute, second, millisecond, " |
| 28 | + "epochMillis, epochSeconds, dayOfWeek, dayOfYear, quarter, formatted" |
| 29 | + ), |
| 30 | + "type": "object", |
| 31 | + }, |
| 32 | + "examples": [ |
| 33 | + "RETURN datetime() AS now", |
| 34 | + "RETURN datetime('2025-06-15T12:30:00Z') AS dt", |
| 35 | + "RETURN datetime({year: 2025, month: 6, day: 15, hour: 12}) AS dt", |
| 36 | + "WITH datetime() AS dt RETURN dt.year, dt.month, dt.day", |
| 37 | + ], |
| 38 | +}) |
| 39 | +class Datetime(Function): |
| 40 | + """Datetime function. |
| 41 | +
|
| 42 | + Returns a datetime value (date + time + timezone offset). |
| 43 | + When called with no arguments, returns the current UTC datetime. |
| 44 | + When called with a string argument, parses it as an ISO 8601 datetime. |
| 45 | + When called with a map argument, constructs a datetime from components. |
| 46 | +
|
| 47 | + Equivalent to Neo4j's datetime() function. |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__(self) -> None: |
| 51 | + super().__init__("datetime") |
| 52 | + self._expected_parameter_count = None |
| 53 | + |
| 54 | + def value(self) -> Any: |
| 55 | + children = self.get_children() |
| 56 | + if len(children) > 1: |
| 57 | + raise ValueError("datetime() accepts at most one argument") |
| 58 | + |
| 59 | + if len(children) == 1: |
| 60 | + d = parse_temporal_arg(children[0].value(), "datetime") |
| 61 | + else: |
| 62 | + d = datetime.now(timezone.utc) |
| 63 | + |
| 64 | + return build_datetime_object(d, utc=True) |
0 commit comments