Reputation: 1
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?
Upvotes: 0
Views: 1433
Reputation: 497
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'
Upvotes: 2