Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to take some action based on comparing two dates. Date 1 is stored in a python variable. Date 2 is retrieved from the database in the select statement. For example I want to retrieve some records from the database where the associated date in the record (in form of the timestamp) is later than the date defined by the python variable. Preferably, I would like the comparison to be in readable date format rather than in timestamps.

I am a beginner with python.

----edit ----- Sorry for being ambiguous. Here's what I am trying to do:

import MySQLdb as mdb from datetime import datetime from datetime import date import time

conn = mdb.connect('localhost','root','root','my_db') cur = conn.cursor()

right_now = date.today()// python date

this is the part which I want to figure out

The database has a table which has timestamp. I want to compare that timestamp with this date and then retrieve records based on that comparison. For example I want to retrieve all records for which timestamp is above this date cur.execute("SELECT created from node WHERE timestamp > right_now") results = cur.fetchall() for row in results: print row

share|improve this question
2  
what have you tried so far? – ch3ka Apr 11 at 18:57

2 Answers

first of all, I guess Date 1 (python variable) is a datetime object. http://docs.python.org/2/library/datetime.html

As far as I have used it, MySQLdb gives you results in a (python) datetime object if the sql type was datetime.

So actually you have nothing to do, you can use python datetime comparison methods with date 1 and date 2.

share|improve this answer
Sorry for being ambiguous. Here's what I am trying to do: – Sumit Saurav Apr 12 at 18:23
seen your edit. What is the SQL type of your "timestamp" column ? If it is datetime, your code should work. – Pixou Apr 13 at 10:10

I am a little bit confused about "comparison to be in readable date format rather than in timestamps". I mean the timestamps is readable enough, right?

If Date 1 is timestamps data, then you just simply do comparison. If not, then convert it to timestamps or convert the date in database to date type, both way works.

If you are asking how to write the code to do the comparison, you would use either '_mysql' or sqlalchemy to help you. The detailed syntax can be found at any where.

Anyway, the question itself is not clear enough, so the answer is blur, too.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.