I am a python newbie and I have an SQL query which I need to run in a python script which extracts data between yesterday's date at 08:00AM UTC and today's date at the same hour. I do not know how to represent the exact date and times in Python. Can someone help please?
Asked
Active
Viewed 1,259 times
0
-
What SQL implementation are you using (e.g. MySQL)? and are you using a db tool like SQLAlchemy? – Phillip Martin Feb 16 '16 at 14:50
-
1Check: http://stackoverflow.com/questions/14291636/what-is-the-proper-way-to-convert-between-mysql-datetime-and-python-timestamp – Eray Balkanli Feb 16 '16 at 15:05
1 Answers
2
You can use datetime.isoformat()
try something like this:
from datetime import datetime
yesterday = datetime(2016,2,15,8,0,0).isoformat(' ')
today = datetime(2016,2,16,8,0,0).isoformat(' ')
cursor.execute("SELECT * FROM MyTABLE WHERE INSTANT BETWEEN '" + yesterday + "' AND '" + today + "'")
More info in here.
In order to calculate today and yesterday (at 08h00) autmatically you can do like this:
from datetime import datetime, timedelta
today = datetime(datetime.now().year, datetime.now().month, datetime.now().day, 8, 0, 0, 0)
yesterday = today - timedelta(days=1)
>>> today.isoformat(' ')
'2016-02-18 08:00:00'
>>> yesterday.isoformat(' ')
'2016-02-17 08:00:00'

Svperstar
- 487
- 2
- 10
-
Thanks for the prompt reply. I am using MySQL and what I am actually trying to do is to set yesterday's date at 08:00 as a variable and today's date at 08:00 into a second variable and then use them in the SQL query so that every time I run the script it will always calculate the data from yesterday's date at 08:00 to today's date at 08:00 – Marcio125 Feb 16 '16 at 16:25
-
`today = datetime(datetime.now().year, datetime.now().month, datetime.now().day, 8, 0, 0, 0)` and `yesterday = today - timedelta(days=1)` don't forget to import datetime and timedelta from `datetime` I added this to my answer. – Svperstar Feb 18 '16 at 12:29