473,387 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

inserting/retriving dates in psycopg

Look at this example:
import psycopg
psycopg.__version__ '1.1.19' import datetime
today = datetime.datetime.today()
co = psycopg.connect('')
cu = co.cursor() cu.execute('CREATE TABLE example (date date)')
cu.execute("INSERT into example VALUES (%s)", (today,)) Traceback (most recent call last):
File "/usr/lib/python2.4/doctest.py", line 1243, in __run
compileflags, 1) in test.globs
File "<doctest __main__[6]>", line 1, in ?
cu.execute("INSERT into example VALUES (%s)", (today,))
ProgrammingError: ERROR: syntax error at or near "17" at character 40

INSERT into example VALUES (2006-01-04 17:19:03.354615)

Is there a smart way of solving this, without stripping the date by
hand?
Also, if I insert the date as a string
cu.execute("INSERT into example VALUES ('2006-01-04')")
co.commit()
I get back a DateTime object (I think a mxDateTime object)
cu.execute("SELECT * from example")
d = cu.fetchone()[0]
print type(d)

<type 'DateTime'>

and NOT a datetime.datetime.

So I need an adaptation mechanism; alternatively it would be enough for
me to be able
to redefine the __str__ representation of psycopg DateTime objects (
which are defined
at C level, so I cannot just override the __str__ method).

Any hints? I am sure there is a custom way to do this.

Michele Simionato

Jan 4 '06 #1
4 3203

Michele Simionato wrote:
Look at this example:
import psycopg
psycopg.__version__ '1.1.19' import datetime
today = datetime.datetime.today()
co = psycopg.connect('')
cu = co.cursor() cu.execute('CREATE TABLE example (date date)')
cu.execute("INSERT into example VALUES (%s)", (today,)) Traceback (most recent call last):
File "/usr/lib/python2.4/doctest.py", line 1243, in __run
compileflags, 1) in test.globs
File "<doctest __main__[6]>", line 1, in ?
cu.execute("INSERT into example VALUES (%s)", (today,))
ProgrammingError: ERROR: syntax error at or near "17" at character 40

INSERT into example VALUES (2006-01-04 17:19:03.354615)

Is there a smart way of solving this, without stripping the date by
hand?
Also, if I insert the date as a string
cu.execute("INSERT into example VALUES ('2006-01-04')")
co.commit()
I get back a DateTime object (I think a mxDateTime object)
cu.execute("SELECT * from example")
d = cu.fetchone()[0]
print type(d)

<type 'DateTime'>

and NOT a datetime.datetime.

So I need an adaptation mechanism; alternatively it would be enough for
me to be able
to redefine the __str__ representation of psycopg DateTime objects (
which are defined
at C level, so I cannot just override the __str__ method).

Any hints? I am sure there is a custom way to do this.

Michele Simionato


I am no expert, but as I have not seen any other replies, I will
explain how I do it.

Firstly, I seem to recall that when you install psycopg, it tries to
guess whether to compile it for mx.DateTime or the built-in datetime
module, based on version of Python, whether mx is installed, etc. I am
sure it is possible to force it to choose your preferred one by
modifying the .cfg file (I think).

Assuming it is set up correctly for the datetime module, this is how I
insert and retrieve.

If I have a datetime.datetime instance called dat, I insert it using
str(dat).

I found retrieving a bit trickier, as I have standardised on using the
datetime.datetime type throughout my app, but I have a mixture of DATE
and TIMESTAMP types in my database. Therefore I convert the result as
follows -

import datetime as dt

def DbToDate(dat):
if isinstance(dat,dt.datetime):
return dat # already in datetime format
if isinstance(dat,dt.date):
return dt.datetime.combine(dat,dt.time(0)) # convert to
datetime

HTH

Frank Millman

Jan 5 '06 #2
Frank Millman:
import datetime as dt def DbToDate(dat):
if isinstance(dat,dt.datetime):
return dat # already in datetime format
if isinstance(dat,dt.date):
return dt.datetime.combine(dat,dt.time(0)) # convert to datetime


This is exactly the type checking I would like to avoid :-/

Michele Simionato

Jan 5 '06 #3

Michele Simionato wrote:
Frank Millman:
import datetime as dt

def DbToDate(dat):
if isinstance(dat,dt.datetime):
return dat # already in datetime format
if isinstance(dat,dt.date):
return dt.datetime.combine(dat,dt.time(0)) # convert to datetime


This is exactly the type checking I would like to avoid :-/

Michele Simionato


psycopg returns a datetime.datetime object from a TIMESTAMP column, and
a datetime.date object from a DATE column. You should not have to do
any type checking unless you are doing something odd, like I am, and
wanting to convert them all into datetime.datetime objects.

Perhaps if you explain what you are trying to do, I may be able to
suggest something.

Frank

Jan 5 '06 #4
Frank Millan:
Perhaps if you explain what you are trying to do, I may be able to
suggest something.


I am looking for an adaptation/type cast mechanism and looking at the
sources I think I have
found it in doc/examples/usercast.py. I am doing some experiment now
....

Michele Simionato

Jan 5 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Alban Hertroys | last post by:
Hello, I'm using psycopg to insert records in a number of threads. After the threads finish, another thread runs to collect the inserted data. Now, my problem is that psycopg let's my threads...
12
by: Alban Hertroys | last post by:
Good day, I have a number of threads doing inserts in a table, after which I want to do a select. This means that it will occur that the row that I want to select is locked (by the DB). In these...
4
by: Alban Hertroys | last post by:
Another python/psycopg question, for which the solution is probably quite simple; I just don't know where to look. I have a query that inserts data originating from an utf-8 encoded XML file....
11
by: Alban Hertroys | last post by:
Oh no! It's me and transactions again :) I'm not really sure whether this is a limitation of psycopg or postgresql. When I use multiple cursors in a transaction, the records inserted at the...
1
by: roderik | last post by:
How do I supress the output generated from each psycopg command: >>> import psycopg initpsycopg: initializing psycopg 1.99.10 typecast_init: initializing NUMBER .. .. microprotocols_add:...
1
by: Eino Mäkitalo | last post by:
I had Visual C++ 6.0, so I compiled those libpq.dll and psycopg.pyd. if there are anyone to play with Windows, Python 2.3 and Postgre-8.0.0-beta4 for windows like me. You cat get those from:...
7
by: jslowery | last post by:
Hello, I'm new to both PostgreSQL and psycopg and I'm trying to connect to my database running on localhost. I have postgres setup to do md5 authentication and this works when using a db admin tool...
1
by: Scott Chapman | last post by:
I am working with Python (psycopg). I have HTML with embedded Python that I'm inserting into a database and it could contain any character. Single quotes, at least, must be escaped (to two...
2
by: Martin P. Hellwig | last post by:
Hi all, I'm playing a bit with PostgreSQL, in which I've set me the target to create a python script which with user input creates a new user role and a database with that owner (connecting to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.