Python django.utils.timezone.is_aware() Examples

The following are 30 code examples for showing how to use django.utils.timezone.is_aware(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: django-healthchecks   Author: mvantellingen   File: admin.py    License: MIT License 6 votes vote down vote up
def last_beat_column(self, object):
        last_beat = object.last_beat
        if is_aware(last_beat):
            # Only for USE_TZ=True
            last_beat = localtime(last_beat)

        last_beat_str = localize(last_beat)
        if object.is_expired:
            # Make clearly visible
            alert_icon = static('admin/img/icon-alert.svg')
            return format_html(
                '<div style="vertical-align: middle; display: inline-block;">'
                '  <img src="{}" style="vertical-align: middle;"> '
                '  <span style="color: #efb80b; vertical-align: middle;">{}</span>'
                '</div>',
                alert_icon, last_beat_str
            )
        else:
            return last_beat_str 
Example 2
Project: python-mysql-pool   Author: LuciferJack   File: operations.py    License: MIT License 6 votes vote down vote up
def value_to_db_datetime(self, value):
        if value is None:
            return None
        # MySQL doesn't support tz-aware times
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = value.astimezone(timezone.utc).replace(tzinfo=None)
            else:
                raise ValueError(
                    "MySQL backend does not support timezone-aware times."
                )
        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)
        if not self.connection.use_pure:
            return datetime_to_mysql(value)
        return self.connection.converter.to_mysql(value) 
Example 3
Project: GTDWeb   Author: lanbing510   File: feedgenerator.py    License: GNU General Public License v2.0 6 votes vote down vote up
def rfc2822_date(date):
    # We can't use strftime() because it produces locale-dependent results, so
    # we have to map english month and day names manually
    months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',)
    days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    # Support datetime objects older than 1900
    date = datetime_safe.new_datetime(date)
    # We do this ourselves to be timezone aware, email.Utils is not tz aware.
    dow = days[date.weekday()]
    month = months[date.month - 1]
    time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month))
    if six.PY2:             # strftime returns a byte string in Python 2
        time_str = time_str.decode('utf-8')
    if is_aware(date):
        offset = date.tzinfo.utcoffset(date)
        timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
        hour, minute = divmod(timezone, 60)
        return time_str + '%+03d%02d' % (hour, minute)
    else:
        return time_str + '-0000' 
Example 4
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 6 votes vote down vote up
def value_to_db_datetime(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = value.astimezone(timezone.utc).replace(tzinfo=None)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example 5
Project: kobo-predict   Author: awemulya   File: sync_deleted_instances_fix.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def handle(self, *args, **kwargs):
        # Reset all sql deletes to None
        Instance.objects.exclude(
            deleted_at=None, xform__downloadable=True).update(deleted_at=None)

        # Get all mongo deletes
        query = '{"$and": [{"_deleted_at": {"$exists": true}}, ' \
                '{"_deleted_at": {"$ne": null}}]}'
        query = json.loads(query)
        xform_instances = settings.MONGO_DB.instances
        cursor = xform_instances.find(query)
        for record in cursor:
            # update sql instance with deleted_at datetime from mongo
            try:
                i = Instance.objects.get(
                    uuid=record["_uuid"],  xform__downloadable=True)
            except Instance.DoesNotExist:
                continue
            else:
                deleted_at = parse_datetime(record["_deleted_at"])
                if not timezone.is_aware(deleted_at):
                    deleted_at = timezone.make_aware(
                        deleted_at, timezone.utc)
                i.set_deleted(deleted_at) 
Example 6
Project: bioforum   Author: reBiocoder   File: operations.py    License: MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example 7
Project: bioforum   Author: reBiocoder   File: operations.py    License: MIT License 6 votes vote down vote up
def adapt_timefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        if isinstance(value, str):
            return datetime.datetime.strptime(value, '%H:%M:%S')

        # Oracle doesn't support tz-aware times
        if timezone.is_aware(value):
            raise ValueError("Oracle backend does not support timezone-aware times.")

        return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
                               value.second, value.microsecond) 
Example 8
Project: bioforum   Author: reBiocoder   File: operations.py    License: MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # MySQL doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")

        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)

        return str(value) 
Example 9
Project: django-compat   Author: arteria   File: json_response.py    License: MIT License 6 votes vote down vote up
def default(self, o):
        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            r = o.isoformat()
            if o.microsecond:
                r = r[:23] + r[26:]
            if r.endswith('+00:00'):
                r = r[:-6] + 'Z'
            return r
        elif isinstance(o, datetime.date):
            return o.isoformat()
        elif isinstance(o, datetime.time):
            if is_aware(o):
                raise ValueError("JSON can't represent timezone-aware times.")
            r = o.isoformat()
            if o.microsecond:
                r = r[:12]
            return r
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, uuid.UUID):
            return str(o)
        else:
            return super(DjangoJSONEncoder, self).default(o) 
Example 10
Project: plugin.video.netflix   Author: CastagnaIT   File: operations.py    License: MIT License 6 votes vote down vote up
def value_to_db_datetime(self, value):
        if value is None:
            return None
        # MySQL doesn't support tz-aware times
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = value.astimezone(timezone.utc).replace(tzinfo=None)
            else:
                raise ValueError(
                    "MySQL backend does not support timezone-aware times."
                )
        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)
        if not self.connection.use_pure:
            return datetime_to_mysql(value)
        return self.connection.converter.to_mysql(value) 
Example 11
Project: django-trackstats   Author: pennersr   File: trackers.py    License: MIT License 6 votes vote down vote up
def get_start_date(self, qs):
        most_recent_kwargs = self.get_most_recent_kwargs()
        last_stat = self.statistic_model.objects.most_recent(
            **most_recent_kwargs)
        if last_stat:
            start_date = last_stat.date
        else:
            first_instance = qs.order_by(self.date_field).first()
            if first_instance is None:
                # No data
                return
            start_date = getattr(first_instance, self.date_field)
        if start_date and isinstance(start_date, datetime):
            if timezone.is_aware(start_date):
                start_date = timezone.make_naive(start_date).date()
            else:
                start_date = start_date.date()
        return start_date 
Example 12
Project: rssant   Author: anyant   File: validator.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def datetime_validator(compiler, format='%Y-%m-%dT%H:%M:%S.%fZ', output_object=False):
    def validate(value):
        try:
            if not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
                if value is None:
                    raise Invalid('not well formatted datetime')
            if not timezone.is_aware(value):
                value = timezone.make_aware(value, timezone=timezone.utc)
            # https://bugs.python.org/issue13305
            if value.year < 1000:
                raise Invalid('not support datetime before year 1000')
            if value.year > 2999:
                raise Invalid('not support datetime after year 2999')
            if output_object:
                return value
            else:
                return value.strftime(format)
        except Invalid:
            raise
        except Exception as ex:
            raise Invalid('invalid datetime') from ex
    return validate 
Example 13
Project: python-ibmdb-django   Author: ibmdb   File: operations.py    License: Apache License 2.0 6 votes vote down vote up
def value_to_db_datetime( self, value ):
        if value is None:
            return None
        
        if( djangoVersion[0:2] <= ( 1, 3 ) ):
            #DB2 doesn't support time zone aware datetime
            if ( value.tzinfo is not None ):
                raise ValueError( "Timezone aware datetime not supported" )
            else:
                return value
        else:
            if is_aware(value):
                if settings.USE_TZ:
                    value = value.astimezone( utc ).replace( tzinfo=None )
                else:
                    raise ValueError( "Timezone aware datetime not supported" )
            return unicode( value ) 
Example 14
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: operations.py    License: MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: operations.py    License: MIT License 6 votes vote down vote up
def adapt_timefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        if isinstance(value, str):
            return datetime.datetime.strptime(value, '%H:%M:%S')

        # Oracle doesn't support tz-aware times
        if timezone.is_aware(value):
            raise ValueError("Oracle backend does not support timezone-aware times.")

        return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
                               value.second, value.microsecond) 
Example 16
Project: mrs   Author: betagouv   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def to_date_datetime(date_or_datetime, hour, minute, second, microsecond):
    mytz = pytz.timezone(settings.TIME_ZONE)
    if isinstance(date_or_datetime, datetime.datetime):
        if timezone.is_aware(date_or_datetime):
            date = date_or_datetime.astimezone(mytz)
        else:
            date = mytz.localize(date_or_datetime)
    elif isinstance(date_or_datetime, datetime.date):
        date = date_or_datetime

    return mytz.localize(
        datetime.datetime(
            date.year,
            date.month,
            date.day,
            hour,
            minute,
            second,
            microsecond,
        )
    ) 
Example 17
Project: zentral   Author: zentralopensource   File: mt_models.py    License: Apache License 2.0 6 votes vote down vote up
def add_field(self, k, v):
        if not isinstance(k, str) or not k:
            raise ValueError("Invalid field name {}".format(k))
        if k in self.fields:
            raise ValueError("Field {} already added".format(k))
        if self.is_empty_value(v):
            return
        elif isinstance(v, int):
            v = str(v)
        elif isinstance(v, datetime):
            if is_aware(v):
                v = make_naive(v)
            v = v.isoformat()
        elif isinstance(v, list):
            assert(all([isinstance(e, str) and len(e) == 40 for e in v]))
        elif not isinstance(v, str):
            raise ValueError("Invalid field value {} for field {}".format(v, k))
        self.fields[k] = v 
Example 18
Project: python-mysql-pool   Author: LuciferJack   File: operations.py    License: MIT License 5 votes vote down vote up
def value_to_db_time(self, value):
        if value is None:
            return None

        # MySQL doesn't support tz-aware times
        if timezone.is_aware(value):
            raise ValueError("MySQL backend does not support timezone-aware "
                             "times.")

        if not self.connection.use_pure:
            return time_to_mysql(value)
        return self.connection.converter.to_mysql(value) 
Example 19
Project: jbox   Author: jpush   File: fields.py    License: MIT License 5 votes vote down vote up
def _value(self):
        date = self.data

        if settings.USE_TZ and isinstance(date, datetime.datetime) and timezone.is_aware(date):
            self.data = timezone.localtime(date)

        return super(DateTimeField, self)._value() 
Example 20
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def to_current_timezone(value):
    """
    When time zone support is enabled, convert aware datetimes
    to naive dateimes in the current time zone for display.
    """
    if settings.USE_TZ and value is not None and timezone.is_aware(value):
        current_timezone = timezone.get_current_timezone()
        return timezone.make_naive(value, current_timezone)
    return value 
Example 21
Project: GTDWeb   Author: lanbing510   File: feedgenerator.py    License: GNU General Public License v2.0 5 votes vote down vote up
def rfc3339_date(date):
    # Support datetime objects older than 1900
    date = datetime_safe.new_datetime(date)
    time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
    if six.PY2:             # strftime returns a byte string in Python 2
        time_str = time_str.decode('utf-8')
    if is_aware(date):
        offset = date.tzinfo.utcoffset(date)
        timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
        hour, minute = divmod(timezone, 60)
        return time_str + '%+03d:%02d' % (hour, minute)
    else:
        return time_str + 'Z' 
Example 22
Project: GTDWeb   Author: lanbing510   File: dateformat.py    License: GNU General Public License v2.0 5 votes vote down vote up
def U(self):
        "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
        if isinstance(self.data, datetime.datetime) and is_aware(self.data):
            return int(calendar.timegm(self.data.utctimetuple()))
        else:
            return int(time.mktime(self.data.timetuple())) 
Example 23
Project: GTDWeb   Author: lanbing510   File: timesince.py    License: GNU General Public License v2.0 5 votes vote down vote up
def timesince(d, now=None, reversed=False):
    """
    Takes two datetime objects and returns the time between d and now
    as a nicely formatted string, e.g. "10 minutes".  If d occurs after now,
    then "0 minutes" is returned.

    Units used are years, months, weeks, days, hours, and minutes.
    Seconds and microseconds are ignored.  Up to two adjacent units will be
    displayed.  For example, "2 weeks, 3 days" and "1 year, 3 months" are
    possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

    Adapted from
    http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    # Convert datetime.date to datetime.datetime for comparison.
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)

    if not now:
        now = datetime.datetime.now(utc if is_aware(d) else None)

    delta = (d - now) if reversed else (now - d)
    # ignore microseconds
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0:
        # d is in the future compared to now, stop processing.
        return avoid_wrapping(ugettext('0 minutes'))
    for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
        count = since // seconds
        if count != 0:
            break
    result = avoid_wrapping(name % count)
    if i + 1 < len(TIMESINCE_CHUNKS):
        # Now get the second item
        seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
        count2 = (since - (seconds * count)) // seconds2
        if count2 != 0:
            result += ugettext(', ') + avoid_wrapping(name2 % count2)
    return result 
Example 24
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def value_to_db_time(self, value):
        """
        Transforms a time value to an object compatible with what is expected
        by the backend driver for time columns.
        """
        if value is None:
            return None
        if timezone.is_aware(value):
            raise ValueError("Django does not support timezone-aware times.")
        return six.text_type(value) 
Example 25
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def value_to_db_datetime(self, value):
        if value is None:
            return None

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = value.astimezone(timezone.utc).replace(tzinfo=None)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return six.text_type(value) 
Example 26
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def value_to_db_time(self, value):
        if value is None:
            return None

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            raise ValueError("SQLite backend does not support timezone-aware times.")

        return six.text_type(value) 
Example 27
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def value_to_db_time(self, value):
        if value is None:
            return None

        if isinstance(value, six.string_types):
            return datetime.datetime.strptime(value, '%H:%M:%S')

        # Oracle doesn't support tz-aware times
        if timezone.is_aware(value):
            raise ValueError("Oracle backend does not support timezone-aware times.")

        return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
                               value.second, value.microsecond) 
Example 28
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def value_to_db_time(self, value):
        if value is None:
            return None

        # MySQL doesn't support tz-aware times
        if timezone.is_aware(value):
            raise ValueError("MySQL backend does not support timezone-aware times.")

        return six.text_type(value) 
Example 29
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            if settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_date'],
                code='invalid_date',
                params={'value': value},
            )

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        ) 
Example 30
Project: django-seed   Author: Brobin   File: tests.py    License: MIT License 5 votes vote down vote up
def test_guess_format_timezone(self):
        test_names = ('something_at', 'something_At', 'gameUpdated_At', 'game_created_at')

        with django_setting('USE_TZ', True):
            for name in test_names:
                value = self.instance.guess_format(name)(datetime.now())
                self.assertTrue(timezone.is_aware(value))

        with django_setting('USE_TZ', False):
            for name in test_names:
                value = self.instance.guess_format(name)(datetime.now())
                self.assertFalse(timezone.is_aware(value))