本文整理汇总了Python中django.utils.timezone.is_aware方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.is_aware方法的具体用法?Python timezone.is_aware怎么用?Python timezone.is_aware使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.timezone
的用法示例。
在下文中一共展示了timezone.is_aware方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: last_beat_column
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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
示例2: value_to_db_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例3: rfc2822_date
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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'
示例4: value_to_db_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例5: handle
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例6: adapt_datetimefield_value
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例7: adapt_timefield_value
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例8: adapt_datetimefield_value
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例9: default
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)
示例10: get_start_date
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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
示例11: datetime_validator
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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
示例12: value_to_db_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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 )
示例13: to_date_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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,
)
)
示例14: add_field
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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
示例15: value_to_db_time
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import is_aware [as 别名]
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)