~psycopg/psycopg/2.0.x

« back to all changes in this revision

Viewing changes to examples/dt.py

  • Committer: Federico Di Gregorio
  • Date: 2009-04-20 22:38:09 UTC
  • Revision ID: fog@erin-20090420223809-y59bb142mo3vadnw
Better detection of PostgreSQL version

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 
19
19
## don't modify anything below tis line (except for experimenting)
20
20
 
21
 
import sys, psycopg
 
21
import sys
 
22
import psycopg2
22
23
import mx.DateTime
23
24
import datetime
24
25
 
 
26
from psycopg2.extensions import adapt
 
27
 
25
28
if len(sys.argv) > 1:
26
29
    DSN = sys.argv[1]
27
30
 
28
31
print "Opening connection using dns:", DSN
29
 
conn = psycopg.connect(DSN)
 
32
conn = psycopg2.connect(DSN)
30
33
curs = conn.cursor()
31
34
 
32
35
try:
33
 
    curs.execute("""CREATE TABLE test_dt (k int4, d date, t time, dt timestamp,
34
 
                                          z interval)""")
 
36
    curs.execute("""CREATE TABLE test_dt (
 
37
                     k int4, d date, t time, dt timestamp, z interval)""")
35
38
except:
36
39
    conn.rollback()
37
40
    curs.execute("DROP TABLE test_dt")
38
 
    curs.execute("""CREATE TABLE test_dt (k int4,
39
 
                                          d date, t time, dt timestamp,
40
 
                                          z interval)""")
 
41
    curs.execute("""CREATE TABLE test_dt (
 
42
                     k int4, d date, t time, dt timestamp, z interval)""")
41
43
conn.commit()
42
44
 
43
45
# build and insert some data using mx.DateTime
48
50
    mx.DateTime.Timestamp(2004, 10, 19, 0, 11, 17.5),
49
51
    mx.DateTime.DateTimeDelta(13, 15, 17, 59.9))
50
52
 
 
53
from psycopg2.extensions import adapt
 
54
import psycopg2.extras
 
55
print adapt(mx1)
 
56
 
51
57
print "Inserting mx.DateTime values..."
52
58
curs.execute("INSERT INTO test_dt VALUES (%s, %s, %s, %s, %s)", mx1)
53
59
 
69
75
    try:
70
76
        # this will work only is psycopg has been compiled with datetime
71
77
        # as the default typecaster for date/time values
72
 
        s = repr(n) + "\n -> " +  repr(x) + "\n -> " + x.isoformat()
 
78
        s = repr(n) + "\n -> " + str(adapt(n)) + \
 
79
            "\n -> " + repr(x) + "\n -> " + x.isoformat()
73
80
    except:
74
 
        s = repr(n) + "\n -> " +  repr(x) + "\n -> " + str(x)
 
81
        s = repr(n) + "\n -> " + str(adapt(n))  + \
 
82
            "\n -> " + repr(x) + "\n -> " + str(x)
75
83
    print s
76
84
print
77
85