Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support day, month and year function for date #1154

Merged
merged 2 commits into from
Jul 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions rdflib/plugins/sparql/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import random
import uuid
import hashlib
import datetime as py_datetime # naming conflict with function within this module

from functools import reduce

Expand Down Expand Up @@ -449,17 +450,17 @@ def Builtin_NOW(e, ctx):


def Builtin_YEAR(e, ctx):
d = datetime(e.arg)
d = date(e.arg)
return Literal(d.year)


def Builtin_MONTH(e, ctx):
d = datetime(e.arg)
d = date(e.arg)
return Literal(d.month)


def Builtin_DAY(e, ctx):
d = datetime(e.arg)
d = date(e.arg)
return Literal(d.day)


Expand Down Expand Up @@ -998,6 +999,17 @@ def datetime(e):
return e.toPython()


def date(e) -> py_datetime.date:
nicholascar marked this conversation as resolved.
Show resolved Hide resolved
if not isinstance(e, Literal):
raise SPARQLError("Non-literal passed as date: %r" % e)
if e.datatype not in (XSD.date, XSD.dateTime):
raise SPARQLError("Literal with wrong datatype passed as date: %r" % e)
result = e.toPython()
if isinstance(result, py_datetime.datetime):
return result.date()
return result
nicholascar marked this conversation as resolved.
Show resolved Hide resolved


def string(s):
"""
Make sure the passed thing is a string literal
Expand Down
36 changes: 36 additions & 0 deletions test/test_sparql_operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import datetime

import nose.tools

import rdflib
from rdflib.plugins.sparql import operators
from rdflib.plugins.sparql import sparql


def test_date_cast():
now = datetime.datetime.now()
today = now.date()

literal = rdflib.Literal(now)
result = operators.date(literal)
assert isinstance(result, datetime.date)
assert result == today

literal = rdflib.Literal(today)
result = operators.date(literal)
assert isinstance(result, datetime.date)
assert result == today


def test_datetime_cast():
now = datetime.datetime.now()
literal = rdflib.Literal(now)
result = operators.datetime(literal)
assert isinstance(result, datetime.datetime)
assert result == now


@nose.tools.raises(sparql.SPARQLError)
def test_datetime_cast_type_error():
literal = rdflib.Literal("2020-01-02")
operators.date(literal)