I have created a table:
cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);")
I inserted a timestamp like this:
timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00")
cursor.execute("INSERT INTO articles VALUES (%s, %s)",
(title, timestamp))
When I run a SELECT statement to retrieve the timestamps, it returns tuples instead:
cursor.execute("SELECT pubDate FROM articles")
rows = cursor.fetchall()
for row in rows:
print(row)
This is the returned row:
(datetime.datetime(2015, 12, 9, 6, 47, 4, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=660, name=None)),)
How can I retrieve the datetime object directly?
I've looked up a few other related questions (see here and here) but can't seem to find the answer. Probably overlooking something simple here but any help would be much appreciated!
Python's datetime
objects are automatically adapted into SQL by psycopg2
, you don't need to stringify them:
cursor.execute("INSERT INTO articles VALUES (%s, %s)",
(title, datetime_obj))
To read the rows returned by a SELECT
you can use the cursor as an iterator, unpacking the row tuples as needed:
cursor.execute("SELECT pubDate FROM articles")
for pub_date, in cursor: # note the comma after `pub_date`
print(pub_date)
After some more googling I think I figured it out. If I change:
print(row)
to
print(row[0])
It actually works. I guess this is because row is a tuple and this is way to unpack the tuple correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With