比较Python中的时间

时间:2012-10-11 06:28:07

标签: python mysql twisted mysql-python

我有以下代码总是从数据库中获取日期,然后它将检查当前时间是否等于数据库中的时间。这个问题不说拍卖会开始!就像它应该的那样。

所以我想如果陈述不对。有人可以帮我正确的方向吗?谢谢!

def startAuctionServer():
    global cursor

    sql = ("SELECT Auction_StartDate closestDate FROM Auctions "
           "WHERE DATE(Auction_StartDate) > '2012-10-09' "
           "ORDER BY Auction_StartDate ASC LIMIT 1")

    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        auction_startdate = row[0]
        print "AUCTION: %s" % auction_startdate

        now = datetime.datetime.now()
        print now.strftime("%Y-%m-%d %H:%M:%S")
        if auction_startdate == now.strftime("%Y-%m-%d %H:%M:%S"):
            # let the auctions begin
            print "Auction begins!"
            reactor.stop()
            return
        else:
            reactor.callLater(0.05, startAuctionServer)


print "Auction Server Started"
reactor.callLater(0, startAuctionServer)
reactor.run()

解决

我想出了我需要做的事情。我使用str来创建值字符串,然后将它们拆分为空格。

我将if更改为:

if str(now.strftime("%Y-%m-%d %H:%M:%S")).split() == str(auction_startdate).split()

现在我为我正在做的事情找到了基础,现在我可以继续我的项目了。

谢谢你们!

1 个答案:

答案 0 :(得分:1)

也许你可以尝试一个不太具体的比较,例如,在日期:

import datetime

auction_startdate = datetime.datetime.strptime('2012-10-11 12:12:12', '%Y-%m-%d %H:%M:%S')

if auction_startdate.date() == datetime.date.today():
    # let the auctions begin
    .... etc ....

或者

if datetime.datetime.now() >= auction_startdate: