问题描述:

I am taking in a DateTimeField from an API with the format of "2016-08-09T02:16:15Z". I am using the code below to parse it and turn it to what I thought was a date time field, but am getting an error from one of my class methods to compare the time. Please see the parsing code below:

time= dateutil.parser.parse(x['MatchTime']) #MatchTime is the ISO 8601 field

The time seems to be pulling correctly, but when I add it to my Game model, pasted below, my is_live method is giving me an error

Game model:

class Game(models.Model):

time = models.DateTimeField(null=True, blank=True)

livePick = models.BooleanField(default=True)

def is_live(self):

now = timezone.now()

now.astimezone(timezone.utc).replace(tzinfo=None)

if now < self.time:

return True

else:

return False

This is the error I am getting when I run the script to add in the Game with the time

line 34, in is_live

if now < self.time:

TypeError: unorderable types: datetime.datetime() < NoneType()

Update:

Time is added to the Game model with the following

g = Game.objects.create(team1=team1, team2=team2)

g.time = time

g.save()

Any help is greatly appreciated. Thank you!

网友答案:

This is happening because time in your model is nullable, and is empty (None) for the model instance for which the comparison fails. This raises an exception when you try to compare it with a datetime object.

You need to account for the null possibility in your logic, e.g.,:

if self.time is not None and now < self.time:
    return True
else:
    return False
相关阅读:
Top