OpenInformix / IfxPy

Informix native Python driver for scalable enterprise and IoT solutions.
Other
46 stars 22 forks source link

Convert INTERVAL types to datetime.timedelta values and vice versa. #5

Closed cypres-it closed 6 years ago

cypres-it commented 6 years ago

The following INTERVAL types are automatically converted between the native Informix data type and the datetime.timedelta type of the Python standsard library:

DAY HOUR MINUTE SECOND DAY TO HOUR DAY TO MINUTE DAY TO SECOND HOUR TO MINUTE HOUR TO SECOND MINUTE TO SECOND

Support for the following INTERVAL types is missing:

YEAR MONTH YEAR TO MONTH

These three types do not fit exactly the datetime.timedelta type of the Python standard library.

cypres-it commented 6 years ago

This is a script I used for testing:

from datetime import timedelta
import IfxPy

conn = IfxPy.connect("<db>","<user>","<pw>")

def test(_type, dt):
    IfxPy.exec_immediate(conn, "drop table if exists t1")
    IfxPy.exec_immediate(conn, "create table t1 (c1 interval {})".format(_type))
    insert = "insert into t1 (c1) values (?)"
    stmt_insert = IfxPy.prepare(conn, insert)
    IfxPy.execute(stmt_insert, (dt,))
    stmt = IfxPy.exec_immediate(conn, "select c1 from t1")
    res = IfxPy.fetch_tuple(stmt)
    while res:
        print "[{}] {} => {} [{}]".format(_type, dt, res[0], res[0].__class__.__name__)
        res = IfxPy.fetch_tuple(stmt)

test("day to day", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("day to hour", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("day to minute", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("day to second", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("hour to hour", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("hour to minute", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("hour to second", timedelta(days=1, hours=1, minutes=1, seconds=1))
test("minute to minute", timedelta(hours=1, minutes=1, seconds=1))
test("minute to second", timedelta(hours=1, minutes=1, seconds=1))
test("second to second", timedelta(minutes=1, seconds=1))
msatyan commented 6 years ago

Thanks