Python django.utils.timezone.is_aware() Examples
The following are 30
code examples of django.utils.timezone.is_aware().
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.utils.timezone
, or try the search function
.
Example #1
Source File: admin.py From django-healthchecks with MIT License | 7 votes |
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
Source File: validator.py From rssant with BSD 3-Clause "New" or "Revised" License | 7 votes |
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 #3
Source File: feedgenerator.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Source File: operations.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Source File: operations.py From python-mysql-pool with MIT License | 6 votes |
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 #6
Source File: sync_deleted_instances_fix.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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 #7
Source File: operations.py From bioforum with MIT License | 6 votes |
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 #8
Source File: operations.py From bioforum with MIT License | 6 votes |
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 #9
Source File: operations.py From bioforum with MIT License | 6 votes |
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 #10
Source File: json_response.py From django-compat with MIT License | 6 votes |
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 #11
Source File: operations.py From plugin.video.netflix with MIT License | 6 votes |
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 #12
Source File: trackers.py From django-trackstats with MIT License | 6 votes |
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 #13
Source File: operations.py From python-ibmdb-django with Apache License 2.0 | 6 votes |
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
Source File: operations.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Source File: operations.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Source File: models.py From mrs with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: mt_models.py From zentral with Apache License 2.0 | 6 votes |
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
Source File: feedgenerator.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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 #19
Source File: xosbase_header.py From xos with Apache License 2.0 | 5 votes |
def fields_differ(self, f1, f2): if ( isinstance(f1, datetime.datetime) and isinstance(f2, datetime.datetime) and (timezone.is_aware(f1) != timezone.is_aware(f2)) ): return True else: return f1 != f2
Example #20
Source File: __init__.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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 #21
Source File: xosbase_header.py From xos with Apache License 2.0 | 5 votes |
def fields_differ(self, f1, f2): if ( isinstance(f1, datetime.datetime) and isinstance(f2, datetime.datetime) and (timezone.is_aware(f1) != timezone.is_aware(f2)) ): return True else: return f1 != f2
Example #22
Source File: dateformat.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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
Source File: raw_parser.py From rssant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _normalize_date(self, value) -> datetime.datetime: if not value: return None try: if isinstance(value, list) and len(value) == 9: value = tuple(value) if isinstance(value, tuple): try: timestamp = time.mktime(value) except OverflowError: return None value = datetime.datetime.fromtimestamp(timestamp, tz=UTC) elif not isinstance(value, datetime.datetime): value = parse_datetime(value) if value is None: return None except Exception as ex: LOG.warning('normalize date failed, value=%r: %s', value, ex) return None if not timezone.is_aware(value): value = timezone.make_aware(value, timezone=UTC) # https://bugs.python.org/issue13305 if value.year < 1000: return None if value.year > 2999: return None return value
Example #24
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_make_aware_explicit_tz(settings): """Tests datetimes are made aware of the given timezone.""" settings.USE_TZ = True given_timezone = pytz.timezone("Asia/Bangkok") datetime_object = datetime(2016, 1, 2, 21, 52, 25) assert timezone.is_naive(datetime_object) datetime_aware = make_aware(datetime_object, tz=given_timezone) assert timezone.is_aware(datetime_aware) assert datetime_aware.tzinfo.zone == given_timezone.zone
Example #25
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_make_naive(settings): """Tests datetimes can be made naive of timezones.""" settings.USE_TZ = True datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc) assert timezone.is_aware(datetime_object) naive_datetime = make_naive(datetime_object) assert timezone.is_naive(naive_datetime)
Example #26
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_make_naive_default_tz(settings): """Tests datetimes are made naive of the configured timezone.""" settings.USE_TZ = True datetime_object = timezone.make_aware( datetime(2016, 1, 2, 21, 52, 25), timezone=pytz.timezone("Europe/Helsinki") ) assert timezone.is_aware(datetime_object) naive_datetime = make_naive(datetime_object) assert timezone.is_naive(naive_datetime) # Conversion from a Helsinki aware datetime to a naive datetime in Amsterdam # should decrement 1 hour (UTC+2 vs. UTC+1) assert naive_datetime.hour == (datetime_object.hour - 1) % 24
Example #27
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_make_naive_use_tz_false(settings): """Tests datetimes are left intact if `USE_TZ` is not in effect.""" settings.USE_TZ = False datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc) assert timezone.is_aware(datetime_object) naive_datetime = make_naive(datetime_object) assert timezone.is_aware(naive_datetime)
Example #28
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_aware_datetime(settings): """Tests the creation of a timezone-aware datetime.""" datetime_object = aware_datetime(2016, 1, 2, 21, 52, 25) assert timezone.is_aware(datetime_object) assert datetime_object.tzinfo.zone == settings.TIME_ZONE
Example #29
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_aware_datetime_explicit_tz(): """Tests the creation of a explicitly provided timezone-aware datetime.""" new_datetime = aware_datetime(2016, 1, 2, 21, 52, 25, tz=pytz.utc) assert timezone.is_aware(new_datetime) assert new_datetime.tzinfo.zone == pytz.utc.zone
Example #30
Source File: timezone.py From zing with GNU General Public License v3.0 | 5 votes |
def test_make_aware_default_tz(settings): """Tests datetimes are made aware of the configured timezone.""" settings.USE_TZ = True datetime_object = datetime(2016, 1, 2, 21, 52, 25) assert timezone.is_naive(datetime_object) datetime_aware = make_aware(datetime_object) assert timezone.is_aware(datetime_aware) # Not comparing `tzinfo` directly because that depends on the combination of # actual date+times assert datetime_aware.tzinfo.zone == timezone.get_default_timezone().zone