Python sqlalchemy.types.DateTime() Examples

The following are 30 code examples of sqlalchemy.types.DateTime(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.types , or try the search function .
Example #1
Source File: base.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #2
Source File: test_autogen_render.py    From alembic with MIT License 6 votes vote down vote up
def test_render_server_default_no_context(self):
        uo = ops.UpgradeOps(
            ops=[
                ops.CreateTableOp(
                    "sometable",
                    [Column("x", types.DateTime(), server_default=func.now())],
                )
            ]
        )

        eq_ignore_whitespace(
            autogenerate.render_python_code(uo),
            "# ### commands auto generated by Alembic - please adjust! ###\n"
            "    op.create_table('sometable',\n"
            "    sa.Column('x', sa.DateTime(), "
            "server_default=sa.text(!U'now()'), nullable=True)\n"
            "    )\n"
            "    # ### end Alembic commands ###",
        ) 
Example #3
Source File: base.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and \
                                self.server_version_info >= (2, )
                            ) or \
                            ('interbase' in self.server_version_info and \
                                self.server_version_info >= (6, )
                            )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two  and \
                            self.__dict__.get('implicit_returning', True) 
Example #4
Source File: test_autogen_render.py    From alembic with MIT License 6 votes vote down vote up
def test_render_server_default_context_passed(self):
        uo = ops.UpgradeOps(
            ops=[
                ops.CreateTableOp(
                    "sometable",
                    [Column("x", types.DateTime(), server_default=func.now())],
                )
            ]
        )
        context = MigrationContext.configure(dialect_name="sqlite")
        eq_ignore_whitespace(
            autogenerate.render_python_code(uo, migration_context=context),
            "# ### commands auto generated by Alembic - please adjust! ###\n"
            "    op.create_table('sometable',\n"
            "    sa.Column('x', sa.DateTime(), "
            "server_default=sa.text(!U'(CURRENT_TIMESTAMP)'), nullable=True)\n"
            "    )\n"
            "    # ### end Alembic commands ###",
        ) 
Example #5
Source File: test_querying.py    From asyncpgsa with Apache License 2.0 6 votes vote down vote up
def test_querying_table(metadata):
    """
    Create an object for test table.

    """

    # When using pytest-xdist, we don't want concurrent table creations
    # across test processes so we assign a unique name for table based on
    # the current worker id.
    worker_id = os.environ.get('PYTEST_XDIST_WORKER', 'master')
    return Table(
        'test_querying_table_' + worker_id, metadata,
        Column('id', types.Integer, autoincrement=True, primary_key=True),
        Column('serial', types.Integer, Sequence("serial_seq")),
        Column('t_string', types.String(60), onupdate='updated'),
        Column('t_list', types.ARRAY(types.String(60))),
        Column('t_enum', types.Enum(MyEnum)),
        Column('t_int_enum', types.Enum(MyIntEnum)),
        Column('t_datetime', types.DateTime()),
        Column('t_date', types.DateTime()),
        Column('t_interval', types.Interval()),
        Column('uniq_uuid', PG_UUID, nullable=False, unique=True, default=uuid4),
    ) 
Example #6
Source File: base.py    From android_universal with MIT License 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #7
Source File: base.py    From jbox with MIT License 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #8
Source File: whoosh_backend.py    From flask-msearch with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fields_map(self, field_type):
        if field_type == "primary":
            return ID(stored=True, unique=True)
        type_map = {
            'date': types.Date,
            'datetime': types.DateTime,
            'boolean': types.Boolean,
            'integer': types.Integer,
            'float': types.Float
        }
        if isinstance(field_type, str):
            field_type = type_map.get(field_type, types.Text)

        if not isinstance(field_type, type):
            field_type = field_type.__class__

        if issubclass(field_type, (types.DateTime, types.Date)):
            return DATETIME(stored=True, sortable=True)
        elif issubclass(field_type, types.Integer):
            return NUMERIC(stored=True, numtype=int)
        elif issubclass(field_type, types.Float):
            return NUMERIC(stored=True, numtype=float)
        elif issubclass(field_type, types.Boolean):
            return BOOLEAN(stored=True)
        return TEXT(stored=True, analyzer=self.analyzer, sortable=False) 
Example #9
Source File: fact_notification_status_dao.py    From notifications-api with MIT License 6 votes vote down vote up
def fetch_notification_status_for_service_for_day(bst_day, service_id):
    return db.session.query(
        # return current month as a datetime so the data has the same shape as the ft_notification_status query
        literal(bst_day.replace(day=1), type_=DateTime).label('month'),
        Notification.notification_type,
        Notification.status.label('notification_status'),
        func.count().label('count')
    ).filter(
        Notification.created_at >= get_london_midnight_in_utc(bst_day),
        Notification.created_at < get_london_midnight_in_utc(bst_day + timedelta(days=1)),
        Notification.service_id == service_id,
        Notification.key_type != KEY_TYPE_TEST
    ).group_by(
        Notification.notification_type,
        Notification.status
    ).all() 
Example #10
Source File: base.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #11
Source File: test_functions.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_extract_expression(self, connection):
        meta = self.metadata
        table = Table("test", meta, Column("dt", DateTime), Column("d", Date))
        meta.create_all(connection)
        connection.execute(
            table.insert(),
            {
                "dt": datetime.datetime(2010, 5, 1, 12, 11, 10),
                "d": datetime.date(2010, 5, 1),
            },
        )
        rs = connection.execute(
            select([extract("year", table.c.dt), extract("month", table.c.d)])
        )
        row = rs.first()
        assert row[0] == 2010
        assert row[1] == 5
        rs.close() 
Example #12
Source File: test_functions.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_replace_function(self):
        class replaceable_func(GenericFunction):
            type = Integer
            identifier = "replaceable_func"

        assert isinstance(func.Replaceable_Func().type, Integer)
        assert isinstance(func.RePlAcEaBlE_fUnC().type, Integer)
        assert isinstance(func.replaceable_func().type, Integer)

        with expect_warnings(
            "The GenericFunction 'replaceable_func' is already registered and "
            "is going to be overridden.",
            regex=False,
        ):

            class replaceable_func_override(GenericFunction):
                type = DateTime
                identifier = "replaceable_func"

        assert isinstance(func.Replaceable_Func().type, DateTime)
        assert isinstance(func.RePlAcEaBlE_fUnC().type, DateTime)
        assert isinstance(func.replaceable_func().type, DateTime) 
Example #13
Source File: base.py    From sqlalchemy with MIT License 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = (
            "firebird" in self.server_version_info
            and self.server_version_info >= (2,)
        ) or (
            "interbase" in self.server_version_info
            and self.server_version_info >= (6,)
        )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names["TIMESTAMP"] = sqltypes.DATE
            self.colspecs = {sqltypes.DateTime: sqltypes.DATE}

        self.implicit_returning = self._version_two and self.__dict__.get(
            "implicit_returning", True
        ) 
Example #14
Source File: test_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_function_default(self):
        t = Table(
            "t",
            self.metadata,
            Column("id", Integer, primary_key=True),
            Column("x", DateTime(), server_default=func.now()),
        )
        t.create(testing.db)
        with testing.db.connect() as conn:
            now = conn.scalar(func.now())
            today = datetime.datetime.today()
            conn.execute(t.insert())
            conn.execute(t.insert().values(x=today))
            eq_(
                conn.execute(select([t.c.x]).order_by(t.c.id)).fetchall(),
                [(now,), (today,)],
            ) 
Example #15
Source File: base.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #16
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_round_trip_sqlite_datetime(self):
        variant = DateTime().with_variant(
            dialects.sqlite.DATETIME(truncate_microseconds=True), "sqlite"
        )

        t = Table("t", self.metadata, Column("x", variant))
        with testing.db.connect() as conn:
            t.create(conn)

            conn.execute(
                t.insert(), x=datetime.datetime(2015, 4, 18, 10, 15, 17, 4839)
            )

            eq_(
                conn.scalar(
                    select([t.c.x]).where(
                        t.c.x
                        == datetime.datetime(2015, 4, 18, 10, 15, 17, 1059)
                    )
                ),
                datetime.datetime(2015, 4, 18, 10, 15, 17),
            ) 
Example #17
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_variant_righthand_coercion_returns_self(self):
        my_datetime_normal = DateTime()
        my_datetime_variant = DateTime().with_variant(
            dialects.sqlite.DATETIME(truncate_microseconds=False), "sqlite"
        )

        tab = table(
            "test",
            column("avalue", my_datetime_normal),
            column("bvalue", my_datetime_variant),
        )
        expr = tab.c.avalue == datetime.datetime(2015, 10, 14, 15, 17, 18)

        is_(expr.right.type._type_affinity, DateTime)
        is_(expr.right.type, my_datetime_normal)

        expr = tab.c.bvalue == datetime.datetime(2015, 10, 14, 15, 17, 18)

        is_(expr.right.type, my_datetime_variant) 
Example #18
Source File: base.py    From planespotter with MIT License 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #19
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_interval_coercion(self):
        expr = column("bar", types.Interval) + column("foo", types.Date)
        eq_(expr.type._type_affinity, types.DateTime)

        expr = column("bar", types.Interval) * column("foo", types.Numeric)
        eq_(expr.type._type_affinity, types.Interval) 
Example #20
Source File: base.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def initialize(self, connection):
        super(FBDialect, self).initialize(connection)
        self._version_two = ('firebird' in self.server_version_info and
                             self.server_version_info >= (2, )
                             ) or \
                            ('interbase' in self.server_version_info and
                                self.server_version_info >= (6, )
                             )

        if not self._version_two:
            # TODO: whatever other pre < 2.0 stuff goes here
            self.ischema_names = ischema_names.copy()
            self.ischema_names['TIMESTAMP'] = sqltypes.DATE
            self.colspecs = {
                sqltypes.DateTime: sqltypes.DATE
            }

        self.implicit_returning = self._version_two and \
            self.__dict__.get('implicit_returning', True) 
Example #21
Source File: convert.py    From dvhb-hybrid with MIT License 5 votes vote down vote up
def __init__(self):
        self._types = {
            # Django internal type => SQLAlchemy type
            'ArrayField': SA_ARRAY,
            'AutoField': sa_types.Integer,
            'BigAutoField': sa_types.BigInteger,
            'BigIntegerField': sa_types.BigInteger,
            'BooleanField': sa_types.Boolean,
            'CharField': sa_types.String,
            'DateField': sa_types.Date,
            'DateTimeField': sa_types.DateTime,
            'DecimalField': sa_types.Numeric,
            'DurationField': sa_types.Interval,
            'FileField': sa_types.String,
            'FilePathField': sa_types.String,
            'FloatField': sa_types.Float,
            'GenericIPAddressField': sa_types.String,
            'IntegerField': sa_types.Integer,
            'JSONField': SA_JSONB,
            'NullBooleanField': sa_types.Boolean,
            'PointField': Geometry,
            'PositiveIntegerField': sa_types.Integer,
            'PositiveSmallIntegerField': sa_types.SmallInteger,
            'SlugField': sa_types.String,
            'SmallIntegerField': sa_types.SmallInteger,
            'TextField': sa_types.Text,
            'TimeField': sa_types.Time,
            'UUIDField': SA_UUID,
            # TODO: Add missing GIS fields
        } 
Example #22
Source File: base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _compare_type_affinity(self, other):
        return other._type_affinity in (sqltypes.DateTime, sqltypes.Date) 
Example #23
Source File: base.py    From sqlalchemy-clickhouse with Apache License 2.0 5 votes vote down vote up
def render_literal_value(self, value, type_):
        value = super(ClickHouseCompiler, self).render_literal_value(value, type_)
        if isinstance(type_, sqltypes.DateTime):
            value = 'toDateTime(%s)' % value
        if isinstance(type_, sqltypes.Date):
            value = 'toDate(%s)' % value
        return value 
Example #24
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def _compare_type_affinity(self, other):
        return other._type_affinity in (sqltypes.DateTime, sqltypes.Date) 
Example #25
Source File: test_sqlite.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_cant_parse_datetime_message(self, connection):
        for (typ, disp) in [
            (Time, "time"),
            (DateTime, "datetime"),
            (Date, "date"),
        ]:
            assert_raises_message(
                ValueError,
                "Couldn't parse %s string." % disp,
                lambda: connection.execute(
                    text("select 'ASDF' as value").columns(value=typ)
                ).scalar(),
            ) 
Example #26
Source File: base.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def _compare_type_affinity(self, other):
        return other._type_affinity in (sqltypes.DateTime, sqltypes.Date) 
Example #27
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_class(cls):
        global tztable, notztable, metadata
        metadata = MetaData(testing.db)

        # current_timestamp() in postgresql is assumed to return
        # TIMESTAMP WITH TIMEZONE

        tztable = Table(
            "tztable",
            metadata,
            Column("id", Integer, primary_key=True),
            Column(
                "date",
                DateTime(timezone=True),
                onupdate=func.current_timestamp(),
            ),
            Column("name", String(20)),
        )
        notztable = Table(
            "notztable",
            metadata,
            Column("id", Integer, primary_key=True),
            Column(
                "date",
                DateTime(timezone=False),
                onupdate=cast(
                    func.current_timestamp(), DateTime(timezone=False)
                ),
            ),
            Column("name", String(20)),
        )
        metadata.create_all() 
Example #28
Source File: test_functions.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_generic_now(self):
        assert isinstance(func.now().type, sqltypes.DateTime)

        for ret, dialect in [
            ("CURRENT_TIMESTAMP", sqlite.dialect()),
            ("now()", postgresql.dialect()),
            ("now()", mysql.dialect()),
            ("CURRENT_TIMESTAMP", oracle.dialect()),
        ]:
            self.assert_compile(func.now(), ret, dialect=dialect) 
Example #29
Source File: test_functions.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_case_sensitive(self):
        class MYFUNC(GenericFunction):
            type = DateTime

        assert isinstance(func.MYFUNC().type, DateTime)
        assert isinstance(func.MyFunc().type, DateTime)
        assert isinstance(func.mYfUnC().type, DateTime)
        assert isinstance(func.myfunc().type, DateTime) 
Example #30
Source File: base.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def _compare_type_affinity(self, other):
        return other._type_affinity in (sqltypes.DateTime, sqltypes.Date)