1 # datetime.py - example of using date and time types
3 # Copyright (C) 2001-2004 Federico Di Gregorio <fog@debian.org>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2, or (at your option) any later
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 ## put in DSN your DSN string
19 ## don't modify anything below tis line (except for experimenting)
26 from psycopg2.extensions import adapt
31 print "Opening connection using dns:", DSN
32 conn = psycopg2.connect(DSN)
36 curs.execute("""CREATE TABLE test_dt (
37 k int4, d date, t time, dt timestamp, z interval)""")
40 curs.execute("DROP TABLE test_dt")
41 curs.execute("""CREATE TABLE test_dt (
42 k int4, d date, t time, dt timestamp, z interval)""")
45 # build and insert some data using mx.DateTime
48 mx.DateTime.Date(2004, 10, 19),
49 mx.DateTime.Time(0, 11, 17.015),
50 mx.DateTime.Timestamp(2004, 10, 19, 0, 11, 17.5),
51 mx.DateTime.DateTimeDelta(13, 15, 17, 59.9))
53 from psycopg2.extensions import adapt
54 import psycopg2.extras
57 print "Inserting mx.DateTime values..."
58 curs.execute("INSERT INTO test_dt VALUES (%s, %s, %s, %s, %s)", mx1)
60 # build and insert some values using the datetime adapters
63 datetime.date(2004, 10, 19),
64 datetime.time(0, 11, 17, 15000),
65 datetime.datetime(2004, 10, 19, 0, 11, 17, 500000),
66 datetime.timedelta(13, 15*3600+17*60+59, 900000))
68 print "Inserting Python datetime values..."
69 curs.execute("INSERT INTO test_dt VALUES (%s, %s, %s, %s, %s)", dt1)
71 # now extract the row from database and print them
72 print "Extracting values inserted with mx.DateTime wrappers:"
73 curs.execute("SELECT d, t, dt, z FROM test_dt WHERE k = 1")
74 for n, x in zip(mx1[1:], curs.fetchone()):
76 # this will work only is psycopg has been compiled with datetime
77 # as the default typecaster for date/time values
78 s = repr(n) + "\n -> " + str(adapt(n)) + \
79 "\n -> " + repr(x) + "\n -> " + x.isoformat()
81 s = repr(n) + "\n -> " + str(adapt(n)) + \
82 "\n -> " + repr(x) + "\n -> " + str(x)
86 print "Extracting values inserted with Python datetime wrappers:"
87 curs.execute("SELECT d, t, dt, z FROM test_dt WHERE k = 2")
88 for n, x in zip(dt1[1:], curs.fetchone()):
90 # this will work only is psycopg has been compiled with datetime
91 # as the default typecaster for date/time values
92 s = repr(n) + "\n -> " + repr(x) + "\n -> " + x.isoformat()
94 s = repr(n) + "\n -> " + repr(x) + "\n -> " + str(x)
98 curs.execute("DROP TABLE test_dt")