3

I use Python and SPARQL to make a scheduled query for a database. I tried to use the python f-string and doc-string to inject today's date in the query, but when I try so, a conflict occurs with SPARQL syntax and the python string.

The better way would be to use SPARQL to get today's date.

In my python file my query looks like this:

query = """
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    SELECT * {
    VALUES (?currentDateString) {(today)}

    FILTER(xsd:date(?dateApplicabilityNode) >= xsd:date(?validDateString) && xsd:date(?dateApplicabilityNode) <= xsd:date(?currentDateString))

    }
    GROUP BY ...
    ORDER BY ...

How to get today's date in the format of "YYYY-MM-DD"?

Mahdi Jafari
  • 347
  • 6
  • 22
  • 2
    getting the current date in Python in the appropriate format has been asked and answered before: https://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-pythonhttps://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-python – UninformedUser Nov 23 '22 at 06:52

1 Answers1

2

now() returns the datetime (as xsd:dateTime) of the query execution:

BIND( now() AS ?currentDateTime ) .

To get only the date (as xsd:string), you could use CONCAT() with year(), month(), and day():

BIND( CONCAT( year(?currentDateTime), "-", month(?currentDateTime), "-", day(?currentDateTime) ) AS ?currentDateString ) .

(To get the date as xsd:date, you could use xsd:date(?currentDateString).)

  • Thanks @Stefan. I replaced the above two lines with the `VALUES (?currentDateString) {(today)}` line, but the query gives me an error. I have updated the query on the question. Could you help me? – Mahdi Jafari Nov 22 '22 at 12:38
  • 1
    @MahdiJafari: Try replacing your `VALUES {}` with my two `BIND` lines, and cast the string `?currentDateString` to `xsd:date()` in your `FILTER`. – Stefan - brox IT-Solutions Nov 22 '22 at 13:55