How to change literals of type xsd:date to xsd:dateTime using Python?

Viewed 38

I have a graph which uses Literals of datatype xsd:date to save dates. However I want to use an .owl version of that graph in a reasoner, and the reasoner only accepts the xsd:dateTime format. Is there any way to change the datatype of my date literals?

I was thinking of using rdflib to get all the date nodes of my graph as such:

for birthday in g.objects(None,URIRef(ns+'hasBirthday')):

and then converting the birthday to xsd:dateTime somehow. But I can't figured out how to do the conversion.

If there was a way to do this in the ontology file, it would also help.

1 Answers

You could create a new xsd:dateTime literal based on the original xsd:date literal.

Here is an example if you want to replace the original triples in the graph with new triples with the converted literal as the object:

from rdflib import Literal, URIRef
from datetime import datetime

for s, p, o in g.triples((None, URIRef('hasBirthday', base=ns), None)):
    d = o.toPython()
    g.add((s, p, Literal(datetime(d.year, d.month, d.day))))
    g.remove((s, p, o))
Related