import pywikibot
from pywikibot import pagegenerators as pg


def wd_sparql_query(spq):
   generator=pg.WikidataSPARQLPageGenerator(spq,site=pywikibot.Site('wikidata','wikidata'))
   for wd in generator:
     try:
       wd.get(get_redirect=True)
       yield wd
     except:
       pass

def get_all_inceptions():
 counter=0
 for wd in wd_sparql_query(query):
    incepted=wd.claims['P571']
    if (len(incepted)>1):
      counter+=1  
      #print(f'{counter}-{wd.title()}-{len(incepted)}')
      delete_one_inception(wd)
      if (counter>2): x=10/0

def delete_one_inception(wd):
 keep=delete=None   
 incepted=wd.claims['P571']
 if (len(incepted)>1):
   for one in incepted:
      ot=one.getTarget()
      if (ot.precision==9):
        delete=one
      if (ot.precision==11):
        keep=one
   #print(keep)
   #print(delete)
   if ((keep!=None) and (delete!=None)):
     wd.removeClaims(delete,summary='see Wikidata:BR: geographical township of Quebec (Q23019040) maintenance') 
        
site = pywikibot.Site('wikidata','wikidata')           #Geef aan naar welke site je wilt schrijven
repo = site.data_repository()                     #voor ophalen wikidata-items adhv Qxxxx
query='select ?item where {?item wdt:P31 wd:Q23019040 . ?item wdt:P571 ?inception}'

print('Start')
get_all_inceptions()
print('Klaar')    
Start
Sleeping for 9.3 seconds, 2019-06-08 20:19:29
Sleeping for 8.3 seconds, 2019-06-08 20:19:40
Exception ignored in: <generator object wd_sparql_query at 0x7f70c75b7e08>
RuntimeError: generator ignored GeneratorExit
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-22-cfbf48d0e923> in <module>
     42 
     43 print('Start')
---> 44 get_all_inceptions()
     45 print('Klaar')

<ipython-input-22-cfbf48d0e923> in get_all_inceptions()
     20       #print(f'{counter}-{wd.title()}-{len(incepted)}')
     21       delete_one_inception(wd)
---> 22       if (counter>2): x=10/0
     23 
     24 def delete_one_inception(wd):

ZeroDivisionError: division by zero