Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 selecting timestamp returns datetime.datetime wrapped in tuple, how to unpack?

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!

like image 243
freefall Avatar asked Dec 09 '15 11:12

freefall


2 Answers

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)
like image 84
Eugene Yarmash Avatar answered Sep 18 '22 22:09

Eugene Yarmash


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.

like image 43
freefall Avatar answered Sep 22 '22 22:09

freefall