python tuple返回datetime.datetime

时间:2015-02-25 16:57:32

标签: python datetime

问题:

每当我得到以下查询的结果时:

"SELECT email, url, `timestamp` FROM `transaction` WHERE `email` != '' AND `timestamp` >= \'" + dateonlystring + "\' AND `timestamp` < DATE(DATE_ADD(\'" + dateonlystring + "\', INTERVAL 1 DAY))"

出现了:

('sampleemail@yahoo.com','http://sample.url.com',datetime.datetime(2015,2,25,10,11,19))

为什么它是datetime.datetime(2015,2,25,10,11,19))?

我怎么能把它变成这个:

sampleemail@yahoo.com〜http://sample.url.com~2015-02-25 10:11:19

我的代码/我尝试的内容:

#Date
#datestamp = datetime.strptime('2015-02-25 00:00:00', "%Y-%m-%d %H:%M:%S")
datestamp = datetime.now()
dateonlystring = str(datestamp.date().strftime("%Y-%m-%d %H:%M:%S"))
datetimestring = str(datestamp.now().strftime("%Y%m%d%H%M%S"))

#Dunchangeme:
#Query:
q_getstuff = "SELECT email, url, `timestamp` FROM `transaction` WHERE `email` != '' AND `timestamp` >= \'" + dateonlystring + "\' AND `timestamp` < DATE(DATE_ADD(\'" + dateonlystring + "\', INTERVAL 1 DAY))"

try:
    con = mdb.connect(hostname, username, password, database)
    cur = con.cursor()
    cur.execute(q_getstuff)
    result = cur.fetchall()

    for row in result:
        tuplecrap = str(row).replace('(', '').replace(')', '').replace('\'', '').replace(', ', '~')
        print tuplecrap

值得注意的是,如果用户打算转到特定日期(而不是现在),那么评论的第一个datestamp就在那里。

最简单的方法是简单地删除括号和逗号,就像我上面所做的那样,但如果不进入复杂的正则表达式解决方案,这并不能解决问题,而且我很确定这不是正确的方法。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

每个结果行中都有3个项目的元组,只需将其解压缩:

for row in result:
    email, url, date = row
    # here you can format date as you want