Search code examples
sparqlwikidatasparqlwrapperwikidata-query-service

Sparql query dates json results in the same format that in web portal


How to get the results related to dates from Sparql queries in wikidata in JSON through Python codes in the same format they appear when I query directly through the web?

When I query in Wikidata Query Portal (Try it), some dates appear formatted like 21 de junho de 1839, but when i request them via Python with the library SPARQLWrapper, they appear this way: 1839-06-21T00:00:00Z. How to get the "beautified version" from site in JSON?


Solution

  • I have slightly modified your query and added it to the wikidata.yaml sample queries of the pyLodStorage library for which i am committer so that

    sparqlquery -qp wikidata.yaml -qn MachadoDeAssis -f github
    

    works and gives the cut&paste result shown further down below.

    sparqlquery -qp wikidata.yaml -qn MachadoDeAssis -f json 
    

    returns

    [
      {
        "author": "http://www.wikidata.org/entity/Q311145",
        "authorLabel": "Machado de Assis",
        "birthDate": "1839-06-21 00:00:00"
      }
    ]
    

    now you can pipe the result thru

    | jq '.[] | .birthDate | strptime("%Y-%m-%d %H:%M:%S") | strftime("%c")'
    
    sparqlquery -qp wikidata.yaml -qn MachadoDeAssis -f json | jq '.[] | .birthDate | strptime("%Y-%m-%d %H:%M:%S") | strftime("%c")'
    

    which results in

    "Fri Jun 21 00:00:00 1839"
    

    if all runs well in a different locale the output should be according to your locale.

    MachadoDeAssis

    query

    # modified by WF 2022-07-22
    PREFIX wd: <http://www.wikidata.org/entity/>
    PREFIX wdt: <http://www.wikidata.org/prop/direct/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?author ?authorLabel ?birthDate
    WHERE 
    {
      VALUES ?authorLabel {
        "Machado de Assis"@pt
      }
      # Instance of Human
      ?author wdt:P31 wd:Q5 .
      # Joaquim Maria Machado de Assis
      ?author rdfs:label ?authorLabel.
      FILTER (LANG(?authorLabel) = "pt").
      # birthDate
      ?author wdt:P569 ?birthDate .
    }
    
    

    try it!

    result

    author authorLabel birthDate
    http://www.wikidata.org/entity/Q311145 Machado de Assis 1839-06-21 00:00:00