Alan Tingey Alan Tingey - 1 year ago 85
MySQL Question

Python date match with MySQL

I have the following code:

fixtures = StraightredFixture.objects.filter(soccerseason=soccerseason,fixturematchday=fixturematchday).order_by('fixturedate')

firstGameTime = str(fixtures[0].fixturedate).split()
currentTime = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")).split()


if firstGameTime >= currentTime:
selectteams = True
else:
selectteams = False


Whatever the date of the firstGameTime is it always returns False. Two examples are as follows:

firstGameTime = ['2010-10-28', '11:30:00+00:00']
currentTime = ['2016-10-29', '10:51:50']
selectteams = False

firstGameTime = ['2010-10-30', '11:30:00+00:00']
currentTime = ['2016-10-29', '10:53:16']
selectteams = False


In the second example I would expect it to say True as the firstGameTime is the 30th whereas the currentTime is the 29th.

I have a feeling it is to do with the +00:00 part but am at a loss on how to fix this. Any help would be appreciated, many thanks, Alan.

Answer Source

Datetimes are directly comparable. There is no need to convert to lists of strings.

firstGameTime = fixtures[0].fixturedate
currentTime = datetime.now()

if firstGameTime >= currentTime:
    ...

However, since this is Django you could do this directly in the query:

selectteams = StraightredFixture.objects.filter(
    soccerseason=soccerseason,
    fixturematchday=fixturematchday
    fixturedate__gte=datetime.now()
).exists()