Python django.db.backends.utils.typecast_timestamp() Examples

The following are 30 code examples of django.db.backends.utils.typecast_timestamp(). 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 django.db.backends.utils , or try the search function .
Example #1
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'year':
        return "%i-01-01 00:00:00" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'hour':
        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    elif lookup_type == 'minute':
        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    elif lookup_type == 'second':
        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) 
Example #2
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
    - An integer number of microseconds
    - A string representing a datetime
    """
    try:
        real_lhs = datetime.timedelta(0, 0, lhs) if isinstance(lhs, int) else backend_utils.typecast_timestamp(lhs)
        real_rhs = datetime.timedelta(0, 0, rhs) if isinstance(rhs, int) else backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #3
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'quarter':
        month_in_quarter = dt.month - (dt.month - 1) % 3
        return '%i-%02i-01' % (dt.year, month_in_quarter)
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'week':
        dt = dt - datetime.timedelta(days=dt.weekday())
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #4
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt 
Example #5
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #6
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt 
Example #7
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
        - An integer number of microseconds
        - A string representing a timedelta object
        - A string representing a datetime
    """
    try:
        if isinstance(lhs, six.integer_types):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, six.integer_types):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #8
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def _sqlite_timestamp_diff(lhs, rhs):
    left = backend_utils.typecast_timestamp(lhs)
    right = backend_utils.typecast_timestamp(rhs)
    return (left - right).total_seconds() * 1000000 
Example #9
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    else:
        return getattr(dt, lookup_type) 
Example #10
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #11
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _sqlite_timestamp_diff(lhs, rhs):
    left = backend_utils.typecast_timestamp(lhs)
    right = backend_utils.typecast_timestamp(rhs)
    return duration_microseconds(left - right) 
Example #12
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
        - An integer number of microseconds
        - A string representing a timedelta object
        - A string representing a datetime
    """
    try:
        if isinstance(lhs, six.integer_types):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, six.integer_types):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #13
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    elif lookup_type == 'week':
        return dt.isocalendar()[1]
    else:
        return getattr(dt, lookup_type) 
Example #14
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #15
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt 
Example #16
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
        - An integer number of microseconds
        - A string representing a timedelta object
        - A string representing a datetime
    """
    try:
        if isinstance(lhs, six.integer_types):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, six.integer_types):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #17
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def _sqlite_timestamp_diff(lhs, rhs):
    left = backend_utils.typecast_timestamp(lhs)
    right = backend_utils.typecast_timestamp(rhs)
    return (left - right).total_seconds() * 1000000 
Example #18
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    elif lookup_type == 'week':
        return dt.isocalendar()[1]
    else:
        return getattr(dt, lookup_type) 
Example #19
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    else:
        return getattr(dt, lookup_type) 
Example #20
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt 
Example #21
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    elif lookup_type == 'week':
        return dt.isocalendar()[1]
    elif lookup_type == 'quarter':
        return math.ceil(dt.month / 3)
    else:
        return getattr(dt, lookup_type) 
Example #22
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _sqlite_timestamp_diff(lhs, rhs):
    left = backend_utils.typecast_timestamp(lhs)
    right = backend_utils.typecast_timestamp(rhs)
    return (left - right).total_seconds() * 1000000 
Example #23
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
    - An integer number of microseconds
    - A string representing a timedelta object
    - A string representing a datetime
    """
    try:
        if isinstance(lhs, int):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, int):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #24
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt 
Example #25
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'quarter':
        month_in_quarter = dt.month - (dt.month - 1) % 3
        return '%i-%02i-01' % (dt.year, month_in_quarter)
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #26
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _sqlite_date_extract(lookup_type, dt):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    elif lookup_type == 'week':
        return dt.isocalendar()[1]
    elif lookup_type == 'quarter':
        return math.ceil(dt.month / 3)
    else:
        return getattr(dt, lookup_type) 
Example #27
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
        - An integer number of microseconds
        - A string representing a timedelta object
        - A string representing a datetime
    """
    try:
        if isinstance(lhs, six.integer_types):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, six.integer_types):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out) 
Example #28
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _sqlite_datetime_extract(lookup_type, dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    else:
        return getattr(dt, lookup_type) 
Example #29
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _sqlite_date_trunc(lookup_type, dt):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if lookup_type == 'year':
        return "%i-01-01" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) 
Example #30
Source File: db.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        db = router.db_for_write(self.cache_model_class)
        table = connections[db].ops.quote_name(self._table)

        with connections[db].cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM %s" % table)
            num = cursor.fetchone()[0]
            now = timezone.now()
            now = now.replace(microsecond=0)
            if timeout is None:
                exp = datetime.max
            elif settings.USE_TZ:
                exp = datetime.utcfromtimestamp(timeout)
            else:
                exp = datetime.fromtimestamp(timeout)
            exp = exp.replace(microsecond=0)
            if num > self._max_entries:
                self._cull(db, cursor, now)
            pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
            b64encoded = base64.b64encode(pickled)
            # The DB column is expecting a string, so make sure the value is a
            # string, not bytes. Refs #19274.
            if six.PY3:
                b64encoded = b64encoded.decode('latin1')
            try:
                # Note: typecasting for datetimes is needed by some 3rd party
                # database backends. All core backends work without typecasting,
                # so be careful about changes here - test suite will NOT pick
                # regressions.
                with transaction.atomic(using=db):
                    cursor.execute("SELECT cache_key, expires FROM %s "
                                   "WHERE cache_key = %%s" % table, [key])
                    result = cursor.fetchone()
                    if result:
                        current_expires = result[1]
                        if (connections[db].features.needs_datetime_string_cast and not
                                isinstance(current_expires, datetime)):
                            current_expires = typecast_timestamp(str(current_expires))
                    exp = connections[db].ops.value_to_db_datetime(exp)
                    if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
                        cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
                                       "WHERE cache_key = %%s" % table,
                                       [b64encoded, exp, key])
                    else:
                        cursor.execute("INSERT INTO %s (cache_key, value, expires) "
                                       "VALUES (%%s, %%s, %%s)" % table,
                                       [key, b64encoded, exp])
            except DatabaseError:
                # To be threadsafe, updates/inserts are allowed to fail silently
                return False
            else:
                return True