Search code examples
python-2.7python-datetimepython-dateutil

TypeError: can't subtract offset-naive and offset-aware datetimes


So I am trying to subtract to datetime object. I got one from using dateutil.parser and the other was from datetime.now(). I keep getting a

TypeError: can't subtract offset-naive and offset-aware datetimes

I checked for solutions but they dont seem to work. Here is the code:

import json
from dateutil import parser
from datetime import *

with open(".log") as dataFile: 
   dataFile.seek(0)
   data = []
   line=dataFile.readline()
   data=json.loads(line)
   data=ast.literal_eval(json.dumps(data))
   last=parser.parse(data["TIME"])
   print datetime.now()-last

Here is the line of data it is reading:

{"TIME": "2017-06-29T15:17:27.663Z"}

Solution

  • Fixed it by changing the print to

    print datetime.utcnow().replace(tzinfo=pytz.UTC)-last