2

The Problem:

Whenever I get the result of the following query:

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

This comes up:

('[email protected]', 'http://sample.url.com', datetime.datetime(2015, 2, 25, 10, 11, 19))

Why is it a datetime.datetime(2015, 2, 25, 10, 11, 19))?

And how can I turn that into this:

[email protected]~http://sample.url.com~2015-02-25 10:11:19

My Code / What I Tried:

#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

Of note is that the commented first datestamp is there if the user intends to go to a specific date (as opposed to only now).

The easiest way would be to simply get rid of the parenthesis and commas, as I did above, but that doesn't solve the problem without going into complex regex solutions, and I'm pretty sure it's not the right way.

Any suggestions?

2
  • Converting the tuple to a string and manipulating it is definitely not the "easiest way". You seem to be aware of the strftime function, why not use that? Commented Feb 25, 2015 at 17:04
  • what is mdb? Why do you use the string formatting instead of parameterized queries? Normally, you should just pass datetime (and preferably -- timezone-aware datetime objects) and the driver should serialize to the format that the sql engine understands. Commented Feb 25, 2015 at 17:15

1 Answer 1

2

You have tuples with 3 items in each result row, just unpack it:

for row in result:
    email, url, date = row
    # here you can format date as you want
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. I did not know you could do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.