Python日期与MySQL匹配

时间:2016-10-29 10:03:02

标签: python mysql

我有以下代码:

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

无论firstGameTime的日期是什么,它总是返回False。两个例子如下:

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

在第二个例子中,我希望它说True,因为firstGameTime是第30个,而currentTime是第29个。

我觉得这与+00:00部分有关,但我对如何解决这个问题感到茫然。任何帮助将不胜感激,非常感谢,艾伦。

1 个答案:

答案 0 :(得分:1)

日期时间可直接比较。无需转换为字符串列表。

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

if firstGameTime >= currentTime:
    ...

但是,由于这是Django,您可以直接在查询中执行此操作:

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