Python django.utils.timezone.get_default_timezone() Examples
The following are 30
code examples of django.utils.timezone.get_default_timezone().
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: test_timezone.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate()
Example #2
Source File: __init__.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_prep_value(self, value): value = super(DateTimeField, self).get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #3
Source File: dateformat.py From bioforum with MIT License | 6 votes |
def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, return an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return str(name)
Example #4
Source File: dateformat.py From bioforum with MIT License | 6 votes |
def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, return an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds
Example #5
Source File: __init__.py From bioforum with MIT License | 6 votes |
def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #6
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def adapt_datetime_with_timezone_support(value, conv): # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL. if settings.USE_TZ: if timezone.is_naive(value): warnings.warn("MySQL received a naive datetime (%s)" " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) value = value.astimezone(timezone.utc).replace(tzinfo=None) return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv) # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like # timedelta in terms of actual behavior as they are signed and include days -- # and Django expects time, so we still need to override that. We also need to # add special handling for SafeText and SafeBytes as MySQLdb's type # checking is too tight to catch those (see Django ticket #6052). # Finally, MySQLdb always returns naive datetime objects. However, when # timezone support is active, Django expects timezone-aware datetime objects.
Example #7
Source File: models.py From django-modelcluster with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_field_value(field, model): if field.remote_field is None: value = field.pre_save(model, add=model.pk is None) # Make datetimes timezone aware # https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1394-L1403 if isinstance(value, datetime.datetime) and settings.USE_TZ: if timezone.is_naive(value): default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone).astimezone(timezone.utc) # convert to UTC value = timezone.localtime(value, timezone.utc) if is_protected_type(value): return value else: return field.value_to_string(model) else: return getattr(model, field.get_attname())
Example #8
Source File: invoice.py From zing with GNU General Public License v3.0 | 6 votes |
def _check_single_paidtask(invoice, amount): server_tz = timezone.get_default_timezone() local_now = timezone.localtime(invoice.now, server_tz) current_month_start = local_now.replace( day=1, hour=0, minute=0, second=0, microsecond=0 ) PaidTask.objects.get( task_type=PaidTaskTypes.CORRECTION, amount=(-1) * amount, datetime=invoice.month_end, description="Carryover to the next month", user=invoice.user, ) PaidTask.objects.get( task_type=PaidTaskTypes.CORRECTION, amount=amount, datetime=current_month_start, description="Carryover from the previous month", user=invoice.user, )
Example #9
Source File: util.py From zing with GNU General Public License v3.0 | 6 votes |
def get_max_month_datetime(dt): """Returns the datetime representing the last second of the month with respect to the `dt` aware datetime. """ days_in_month = calendar.monthrange(dt.year, dt.month)[1] tz = timezone.get_default_timezone() new_dt = tz.normalize(dt.replace(day=days_in_month),) # DST adjustments could have shifted the month or day if new_dt.month != dt.month: new_dt = new_dt.replace(month=dt.month) if new_dt.day != days_in_month: new_dt = new_dt.replace(day=days_in_month) return new_dt.replace(hour=23, minute=59, second=59, microsecond=0)
Example #10
Source File: pybase.py From python-ibmdb-django with Apache License 2.0 | 6 votes |
def _format_parameters( self, parameters ): parameters = list( parameters ) for index in range( len( parameters ) ): # With raw SQL queries, datetimes can reach this function # without being converted by DateTimeField.get_db_prep_value. if settings.USE_TZ and isinstance( parameters[index], datetime.datetime ): param = parameters[index] if timezone.is_naive( param ): warnings.warn(u"Received a naive datetime (%s)" u" while time zone support is active." % param, RuntimeWarning) default_timezone = timezone.get_default_timezone() param = timezone.make_aware( param, default_timezone ) param = param.astimezone(timezone.utc).replace(tzinfo=None) parameters[index] = param return tuple( parameters ) # Over-riding this method to modify SQLs which contains format parameter to qmark.
Example #11
Source File: dateformat.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, return an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return str(name)
Example #12
Source File: base.py From django-anonymizer with MIT License | 6 votes |
def datetime(self, field=None, val=None): """ Returns a random datetime. If 'val' is passed, a datetime within two years of that date will be returned. """ if val is None: def source(): tzinfo = get_default_timezone() if settings.USE_TZ else None return datetime.fromtimestamp(randrange(1, 2100000000), tzinfo) else: def source(): tzinfo = get_default_timezone() if settings.USE_TZ else None return datetime.fromtimestamp(int(val.strftime("%s")) + randrange(-365*24*3600*2, 365*24*3600*2), tzinfo) return self.get_allowed_value(source, field)
Example #13
Source File: __init__.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #14
Source File: dateformat.py From python with Apache License 2.0 | 6 votes |
def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return six.text_type(name)
Example #15
Source File: dateformat.py From python with Apache License 2.0 | 6 votes |
def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds
Example #16
Source File: __init__.py From python with Apache License 2.0 | 6 votes |
def get_prep_value(self, value): value = super(DateTimeField, self).get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #17
Source File: base.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def adapt_datetime_with_timezone_support(value, conv): # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL. if settings.USE_TZ: if timezone.is_naive(value): warnings.warn("MySQL received a naive datetime (%s)" " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) value = value.astimezone(timezone.utc).replace(tzinfo=None) return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv) # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like # timedelta in terms of actual behavior as they are signed and include days -- # and Django expects time, so we still need to override that. We also need to # add special handling for SafeText and SafeBytes as MySQLdb's type # checking is too tight to catch those (see Django ticket #6052). # Finally, MySQLdb always returns naive datetime objects. However, when # timezone support is active, Django expects timezone-aware datetime objects.
Example #18
Source File: __init__.py From luscan-devel with GNU General Public License v2.0 | 6 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: msg = self.error_messages['invalid_date'] % value raise exceptions.ValidationError(msg) msg = self.error_messages['invalid'] % value raise exceptions.ValidationError(msg)
Example #19
Source File: dateformat.py From openhgsenti with Apache License 2.0 | 6 votes |
def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return six.text_type(name)
Example #20
Source File: dateformat.py From openhgsenti with Apache License 2.0 | 6 votes |
def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds
Example #21
Source File: __init__.py From openhgsenti with Apache License 2.0 | 6 votes |
def get_prep_value(self, value): value = super(DateTimeField, self).get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #22
Source File: dateformat.py From python2017 with MIT License | 6 votes |
def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return six.text_type(name)
Example #23
Source File: dateformat.py From python2017 with MIT License | 6 votes |
def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds
Example #24
Source File: __init__.py From python2017 with MIT License | 6 votes |
def get_prep_value(self, value): value = super(DateTimeField, self).get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value
Example #25
Source File: test_writer.py From django-sqlserver with MIT License | 6 votes |
def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.utcnow()) self.assertSerializedEqual(datetime.datetime.utcnow) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual(datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone())) self.assertSerializedEqual(datetime.datetime(2013, 12, 31, 22, 1, tzinfo=FixedOffset(180))) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {'import datetime'}) ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc)", {'import datetime', 'from django.utils.timezone import utc'}, ) )
Example #26
Source File: test_writer.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.utcnow()) self.assertSerializedEqual(datetime.datetime.utcnow) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual(datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone())) self.assertSerializedEqual(datetime.datetime(2013, 12, 31, 22, 1, tzinfo=FixedOffset(180))) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {'import datetime'}) ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc)", {'import datetime', 'from django.utils.timezone import utc'}, ) )
Example #27
Source File: dateformat.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, return an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds
Example #28
Source File: dateformat.py From python with Apache License 2.0 | 5 votes |
def I(self): # NOQA: E743 "'1' if Daylight Savings Time, '0' otherwise." try: if self.timezone and self.timezone.dst(self.data): return '1' else: return '0' except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return ''
Example #29
Source File: dateformat.py From bioforum with MIT License | 5 votes |
def I(self): # NOQA: E743 "'1' if Daylight Savings Time, '0' otherwise." try: if self.timezone and self.timezone.dst(self.data): return '1' else: return '0' except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return ''
Example #30
Source File: upcoming.py From django-happenings with BSD 2-Clause "Simplified" License | 5 votes |
def _yearly(self): num = self.num year = self.now.year if self.event.l_start_date > self.now: # event starts in the future year = self.event.l_start_date.year elif self.now.month > self.event.l_start_date.month: year += 1 # The event occurs this month, so check the day to see if passed elif self.now.month == self.event.l_start_date.month: # if the current day is > event day, or if the event was today but # finished, increment the year. if self.now.day > self.event.l_start_date.day or \ self.now.day == self.event.l_start_date.day and \ self.now.time() > self.event.l_start_date.time(): year += 1 month = self.event.l_start_date.month day = self.event.l_start_date.day while num: try: start = make_aware( datetime(year, month, day), get_default_timezone() ) # change to date() so we can compare to event.end_repeat start_ = date(year, month, day) # value error most likely means that the event's start date doesn't # appear this calendar month except ValueError: year += 1 continue if self.we_should_stop(start, start_): return self.events.append((start, self.event)) year += 1 num -= 1