• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python func.current_timestamp函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlalchemy.func.current_timestamp函数的典型用法代码示例。如果您正苦于以下问题:Python current_timestamp函数的具体用法?Python current_timestamp怎么用?Python current_timestamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了current_timestamp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_previsions

    def get_previsions(cls, session, end_date=None):
        """ Retrieve future validated requests per user """

        # Searching for requests with an timeframe
        #         [NOW()] ---------- ([end_date])?
        # exemples:
        #      <f --r1---- t>
        #                 <f --r2-- t>
        #                       <f ------r3-------- t>
        #      <f ----------- r4 -------------------- t>
        # => Matching period are periods ending after NOW()
        #   and if an end_date is specified periods starting before it:

        if end_date:
            future_requests = session.query(cls.user_id,func.sum(cls.days)).\
                                filter(cls.date_to >= func.current_timestamp(),
                                        cls.date_from < end_date,
                                       cls.vacation_type_id == 1,
                                       cls.status == 'APPROVED_ADMIN').\
                                    group_by(cls.user_id).\
                                    order_by(cls.user_id);
        else:
            future_requests = session.query(cls.user_id,func.sum(cls.days)).\
                                filter(cls.date_to >= func.current_timestamp(),
                                       cls.vacation_type_id == 1,
                                       cls.status == 'APPROVED_ADMIN').\
                                    group_by(cls.user_id).\
                                    order_by(cls.user_id);

        ret = {}
        for user_id, total in future_requests:
            ret[user_id] = total

        return ret
开发者ID:doyousoft,项目名称:pyvac,代码行数:34,代码来源:models.py


示例2: test_three

    def test_three(self):
        t = self.tables.t

        actual_ts = testing.db.scalar(func.current_timestamp()) - datetime.timedelta(days=5)
        self._test(
            func.current_timestamp() - datetime.timedelta(days=5),
            {"hour": actual_ts.hour, "year": actual_ts.year, "month": actual_ts.month},
        )
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:8,代码来源:test_query.py


示例3: add_ralert_to_to_database

def add_ralert_to_to_database(session):
    for adven in ralert_to_add:
        print("Adventure Name: \'%s\', Type: \'%d\'" % (adven[0], adven[1]))
        new_alert = RescueAlert(adven[0],adven[1], func.current_timestamp(), func.current_timestamp())
        user = session.query(User).filter_by(email=adven[2]).first()
        user.rescue_alerts.append(new_alert)
        session.add(user)

    session.commit()
开发者ID:deelaws,项目名称:AlertWeb,代码行数:9,代码来源:create_sample_adventures.py


示例4: test_twelve

    def test_twelve(self):
        t = self.tables.t
        actual_ts = testing.db.scalar(func.current_timestamp()).replace(tzinfo=None) - datetime.datetime(
            2012, 5, 10, 12, 15, 25
        )

        self._test(
            func.current_timestamp() - func.coalesce(t.c.dtme, func.current_timestamp()), {"day": actual_ts.days}
        )
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:9,代码来源:test_query.py


示例5: valid_login

def valid_login(u_account):
    """Check if current login pass is acceptable.
    User can login by name, mobile or email.
    Returns a dict {id, name, privilege} if valid."""
    query_str = ''
    if u_account['name']:
        query_str = 'name="' + u_account['name'] + '"'
    elif u_account['mobile']:
        query_str = 'mobile="' + u_account['mobile'] + '"'
    elif u_account['email']:
        query_str = 'email="' + u_account['email'] + '"'
    if not query_str or not u_account['pwd']:
        #Error user info, return 1 is safe
        return '无效的用户名和密码格式'
    query_str += ' and passwd="' + u_account['pwd'] + '"'
    session = open_session()
    try:
        u = session.query(User).filter(query_str).first()
        if u == None:
            return '用户名或密码错误。'
        u.lastactive = func.current_timestamp()
        session.merge(u)
        session.commit()
        return {'id': u.id, 'name': u.name, 'privilege': u.privilege}
    except Exception, ex:
        print ex
        return '出错了,请重试。'
开发者ID:lemori,项目名称:study,代码行数:27,代码来源:util_db.py


示例6: get_dag_duration_info

def get_dag_duration_info():
    '''get duration of currently running DagRuns
    :return dag_info
    '''
    driver = Session.bind.driver
    durations = {
        'pysqlite': func.sum(
            (func.julianday(func.current_timestamp()) - func.julianday(DagRun.start_date)) * 86400.0
        ),
        'mysqldb': func.sum(func.timestampdiff(text('second'), DagRun.start_date, func.now())),
        'default': func.sum(func.now() - DagRun.start_date)
    }
    duration = durations.get(driver, durations['default'])

    with session_scope(Session) as session:
        return session.query(
            DagRun.dag_id,
            DagRun.run_id,
            duration.label('duration')
        ).group_by(
            DagRun.dag_id,
            DagRun.run_id
        ).filter(
            DagRun.state == State.RUNNING
        ).all()
开发者ID:slash-cyberpunk,项目名称:airflow-exporter,代码行数:25,代码来源:prometheus_exporter.py


示例7: register_changes

 def register_changes(self, memento_changes):
     """Create rows in the memento table
     :param memento_changes: an iterator over `memento_change` tuples that 
     need to be stored in the memento table.
     """
     rows = list()
     authentication_id = self._get_authentication_id()
     for m in memento_changes:
         if len(m.primary_key) == 1:
             rows.append(
                 {
                     "model": m.model,
                     "primary_key": m.primary_key[0],
                     "previous_attributes": m.previous_attributes,
                     "memento_type": self.memento_id_by_type.get(m.memento_type, None),
                     "authentication_id": authentication_id,
                 }
             )
     if len(rows):
         table = self._get_memento_table()
         clause = table.insert(creation_date=func.current_timestamp())
         try:
             clause.execute(rows)
         except exc.DatabaseError, e:
             LOGGER.error("Programming Error, could not flush history", exc_info=e)
开发者ID:jeroendierckx,项目名称:Camelot,代码行数:25,代码来源:memento.py


示例8: test_compile

    def test_compile(self):
        for dialect in all_dialects(exclude=("sybase",)):
            bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
            self.assert_compile(
                func.current_timestamp(), "CURRENT_TIMESTAMP", dialect=dialect
            )
            self.assert_compile(func.localtime(), "LOCALTIME", dialect=dialect)
            if dialect.name in ("firebird",):
                self.assert_compile(
                    func.nosuchfunction(), "nosuchfunction", dialect=dialect
                )
            else:
                self.assert_compile(
                    func.nosuchfunction(), "nosuchfunction()", dialect=dialect
                )

            # test generic function compile
            class fake_func(GenericFunction):
                __return_type__ = sqltypes.Integer

                def __init__(self, arg, **kwargs):
                    GenericFunction.__init__(self, arg, **kwargs)

            self.assert_compile(
                fake_func("foo"),
                "fake_func(%s)"
                % bindtemplate
                % {"name": "fake_func_1", "position": 1},
                dialect=dialect,
            )

            functions._registry['_default'].pop('fake_func')
开发者ID:monetate,项目名称:sqlalchemy,代码行数:32,代码来源:test_functions.py


示例9: test_compile

    def test_compile(self):
        for dialect in all_dialects(exclude=('sybase', )):
            bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
            self.assert_compile(func.current_timestamp(),
                                "CURRENT_TIMESTAMP", dialect=dialect)
            self.assert_compile(func.localtime(), "LOCALTIME", dialect=dialect)
            if dialect.name in ('firebird',):
                self.assert_compile(func.nosuchfunction(),
                                    "nosuchfunction", dialect=dialect)
            else:
                self.assert_compile(func.nosuchfunction(),
                                    "nosuchfunction()", dialect=dialect)

            # test generic function compile
            class fake_func(GenericFunction):
                __return_type__ = sqltypes.Integer

                def __init__(self, arg, **kwargs):
                    GenericFunction.__init__(self, arg, **kwargs)

            self.assert_compile(
                fake_func('foo'),
                "fake_func(%s)" %
                bindtemplate % {'name': 'fake_func_1', 'position': 1},
                dialect=dialect)
开发者ID:cpcloud,项目名称:sqlalchemy,代码行数:25,代码来源:test_functions.py


示例10: disable

    def disable(self, ends_at=None):
        if ends_at is None:
            ends_at = object_session(self).query(func.current_timestamp()).scalar()

        if self.begins_at is not None and self.begins_at > ends_at:
            self.ends_at = self.begins_at
        else:
            self.ends_at = ends_at
开发者ID:agdsn,项目名称:pycroft,代码行数:8,代码来源:user.py


示例11: end_website_run

 def end_website_run(self, website_run_id):
     upd = ( self.website_run.update().
                 where(
                     self.website_run.c.website_run_id == website_run_id ).
                 values(
                     end_time=func.current_timestamp() )
           )
     result = self.conn.execute(upd)
开发者ID:anukat2015,项目名称:snac,代码行数:8,代码来源:crawl_websites.py


示例12: get_last_applied_membership_fee

def get_last_applied_membership_fee():
    """
    Get the last applied membership fee.
    :rtype: MembershipFee
    """
    return MembershipFee.q.filter(
        MembershipFee.ends_on <= func.current_timestamp()) \
        .order_by(MembershipFee.ends_on.desc()).first()
开发者ID:agdsn,项目名称:pycroft,代码行数:8,代码来源:finance.py


示例13: test_rename_column_serv_compiled_default

 def test_rename_column_serv_compiled_default(self):
     context = op_fixture('mysql')
     op.alter_column('t1', 'c1', new_column_name="c2", existing_type=Integer,
             existing_server_default=func.utc_thing(func.current_timestamp()))
     # this is not a valid MySQL default but the point is to just
     # test SQL expression rendering
     context.assert_(
         "ALTER TABLE t1 CHANGE c1 c2 INTEGER NULL DEFAULT utc_thing(CURRENT_TIMESTAMP)"
     )
开发者ID:Frozenball,项目名称:alembic,代码行数:9,代码来源:test_mysql.py


示例14: test_constructor

    def test_constructor(self):
        try:
            func.current_timestamp('somearg')
            assert False
        except TypeError:
            assert True

        try:
            func.char_length('a', 'b')
            assert False
        except TypeError:
            assert True

        try:
            func.char_length()
            assert False
        except TypeError:
            assert True
开发者ID:cpcloud,项目名称:sqlalchemy,代码行数:18,代码来源:test_functions.py


示例15: upgrade

def upgrade():
    print "... Create TABLE hebergement_video"
    op.create_table(
        'hebergement_video',
        Column('heb_vid_pk', Integer, primary_key=True, unique=True,
               nullable=False),
        Column('heb_vid_url', String()),
        Column('heb_vid_date', Date(), default=func.current_timestamp()),
        Column('heb_vid_heb_fk', Integer, ForeignKey('hebergement.heb_pk'))
    )
开发者ID:gitesdewallonie,项目名称:gites.db,代码行数:10,代码来源:abb9cde33d6_create_hebergement_video.py


示例16: active

    def active(self, when=None):
        """
        Tests if the membership overlaps with a given interval. If no interval
        is given, it tests if the membership is active right now.
        :param Interval when: interval in which the membership
        :rtype: bool
        """
        if when is None:
            now = object_session(self).query(func.current_timestamp()).scalar()
            when = single(now)

        return when.overlaps(closed(self.begins_at, self.ends_at))
开发者ID:agdsn,项目名称:pycroft,代码行数:12,代码来源:user.py


示例17: test_no_paren_fns

 def test_no_paren_fns(self):
     for fn, expected in [
         (func.uid(), "uid"),
         (func.UID(), "UID"),
         (func.sysdate(), "sysdate"),
         (func.row_number(), "row_number()"),
         (func.rank(), "rank()"),
         (func.now(), "CURRENT_TIMESTAMP"),
         (func.current_timestamp(), "CURRENT_TIMESTAMP"),
         (func.user(), "USER"),
     ]:
         self.assert_compile(fn, expected)
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:12,代码来源:test_compiler.py


示例18: play_with_time

def play_with_time(session, name):
    user = session.query(User).filter_by(email='[email protected]').first()

    new_alert = RescueAlert(name, 
                            AdventureType.SnowBoarding.value, 
                            func.current_timestamp(), 
                            get_time_plus_minutes(30))
                            #func.current_timestamp().op('AT TIME ZONE')('UTC'))
                            #func.current_timestamp())
    user.rescue_alerts.append(new_alert)
    session.add(user)
    session.commit()
开发者ID:deelaws,项目名称:AlertWeb,代码行数:12,代码来源:create_sample_adventures.py


示例19: create_table

	def create_table(self):
		Table(
			OPLOG_TABLENAME,
			MetaData(bind = self.engine),
			Column('id', Integer, autoincrement=True, nullable=False, primary_key=True),
			Column('time', TIMESTAMP, default=func.current_timestamp(), nullable=False, index=True),
			Column('user', VARCHAR(32), nullable=False, index=True),
			Column('action', Text, nullable=False),
			Column('args', Text, nullable=True),
			Column('others', Text, nullable=True),
			mysql_engine = 'InnoDB',
			mysql_charset = 'utf8',
		).create(checkfirst = True)
开发者ID:jackdai123,项目名称:pylogagent,代码行数:13,代码来源:logagent_utils.py


示例20: _baseline_5_aggregates

    def _baseline_5_aggregates(self):
        Animal = self.metadata.tables["Animal"]
        Zoo = self.metadata.tables["Zoo"]

        # TODO: convert to ORM
        engine = self.metadata.bind
        for x in range(ITERATIONS):

            # views

            view = engine.execute(select([Animal.c.Legs])).fetchall()
            legs = sorted([x[0] for x in view])
            expected = {
                "Leopard": 73.5,
                "Slug": 0.75,
                "Tiger": None,
                "Lion": None,
                "Bear": None,
                "Ostrich": 103.2,
                "Centipede": None,
                "Emperor Penguin": None,
                "Adelie Penguin": None,
                "Millipede": None,
                "Ape": None,
                "Tick": None,
            }
            for species, lifespan in engine.execute(
                select([Animal.c.Species, Animal.c.Lifespan])
            ).fetchall():
                assert lifespan == expected[species]
            expected = ["Montr\xe9al Biod\xf4me", "Wild Animal Park"]
            e = select(
                [Zoo.c.Name],
                and_(
                    Zoo.c.Founded != None,  # noqa
                    Zoo.c.Founded <= func.current_timestamp(),
                    Zoo.c.Founded >= datetime.date(1990, 1, 1),
                ),
            )
            values = [val[0] for val in engine.execute(e).fetchall()]
            assert set(values) == set(expected)

            # distinct

            legs = [
                x[0]
                for x in engine.execute(
                    select([Animal.c.Legs], distinct=True)
                ).fetchall()
            ]
            legs.sort()
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:51,代码来源:test_zoomark_orm.py



注:本文中的sqlalchemy.func.current_timestamp函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python func.date函数代码示例发布时间:2022-05-27
下一篇:
Python func.current_date函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap