inserting/retriving dates in psycopg

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michele Simionato

    #1

    inserting/retriving dates in psycopg

    Look at this example:
    [color=blue][color=green][color=darkred]
    >>> import psycopg
    >>> psycopg.__versi on__[/color][/color][/color]
    '1.1.19'[color=blue][color=green][color=darkred]
    >>> import datetime
    >>> today = datetime.dateti me.today()
    >>> co = psycopg.connect ('')
    >>> cu = co.cursor()[/color][/color][/color]
    [color=blue][color=green][color=darkred]
    >>> cu.execute('CRE ATE TABLE example (date date)')
    >>> cu.execute("INS ERT into example VALUES (%s)", (today,))[/color][/color][/color]
    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("INS ERT into example VALUES (%s)", (today,))
    ProgrammingErro r: 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
    [color=blue][color=green][color=darkred]
    >>> cu.execute("INS ERT into example VALUES ('2006-01-04')")
    >>> co.commit()[/color][/color][/color]

    I get back a DateTime object (I think a mxDateTime object)
    [color=blue][color=green][color=darkred]
    >>> cu.execute("SEL ECT * from example")
    >>> d = cu.fetchone()[0]
    >>> print type(d)[/color][/color][/color]
    <type 'DateTime'>

    and NOT a datetime.dateti me.

    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

  • Frank Millman

    #2
    Re: inserting/retriving dates in psycopg


    Michele Simionato wrote:[color=blue]
    > Look at this example:
    >[color=green][color=darkred]
    > >>> import psycopg
    > >>> psycopg.__versi on__[/color][/color]
    > '1.1.19'[color=green][color=darkred]
    > >>> import datetime
    > >>> today = datetime.dateti me.today()
    > >>> co = psycopg.connect ('')
    > >>> cu = co.cursor()[/color][/color]
    >[color=green][color=darkred]
    > >>> cu.execute('CRE ATE TABLE example (date date)')
    > >>> cu.execute("INS ERT into example VALUES (%s)", (today,))[/color][/color]
    > 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("INS ERT into example VALUES (%s)", (today,))
    > ProgrammingErro r: 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
    >[color=green][color=darkred]
    > >>> cu.execute("INS ERT into example VALUES ('2006-01-04')")
    > >>> co.commit()[/color][/color]
    >
    > I get back a DateTime object (I think a mxDateTime object)
    >[color=green][color=darkred]
    > >>> cu.execute("SEL ECT * from example")
    > >>> d = cu.fetchone()[0]
    > >>> print type(d)[/color][/color]
    > <type 'DateTime'>
    >
    > and NOT a datetime.dateti me.
    >
    > 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[/color]

    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.dateti me instance called dat, I insert it using
    str(dat).

    I found retrieving a bit trickier, as I have standardised on using the
    datetime.dateti me 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.com bine(dat,dt.tim e(0)) # convert to
    datetime

    HTH

    Frank Millman

    Comment

    • Michele Simionato

      #3
      Re: inserting/retriving dates in psycopg

      Frank Millman:
      [color=blue]
      > import datetime as dt[/color]
      [color=blue]
      > def DbToDate(dat):
      > if isinstance(dat, dt.datetime):
      > return dat # already in datetime format
      > if isinstance(dat, dt.date):
      > return dt.datetime.com bine(dat,dt.tim e(0)) # convert to datetime[/color]

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

      Michele Simionato

      Comment

      • Frank Millman

        #4
        Re: inserting/retriving dates in psycopg


        Michele Simionato wrote:[color=blue]
        > Frank Millman:
        >[color=green]
        > > import datetime as dt[/color]
        >[color=green]
        > > def DbToDate(dat):
        > > if isinstance(dat, dt.datetime):
        > > return dat # already in datetime format
        > > if isinstance(dat, dt.date):
        > > return dt.datetime.com bine(dat,dt.tim e(0)) # convert to datetime[/color]
        >
        > This is exactly the type checking I would like to avoid :-/
        >
        > Michele Simionato[/color]

        psycopg returns a datetime.dateti me 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.dateti me objects.

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

        Frank

        Comment

        • Michele Simionato

          #5
          Re: inserting/retriving dates in psycopg

          Frank Millan:[color=blue]
          > Perhaps if you explain what you are trying to do, I may be able to
          > suggest something.[/color]

          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

          Comment

          Working...