本文整理汇总了Python中django.utils.timezone.utc方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.utc方法的具体用法?Python timezone.utc怎么用?Python timezone.utc使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.timezone
的用法示例。
在下文中一共展示了timezone.utc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: seed_course_overviews
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def seed_course_overviews(data=None):
if not data:
data = cans.COURSE_OVERVIEW_DATA
# append with randomly generated course overviews to test pagination
new_courses = [generate_course_overview(i, org='FOO') for i in xrange(20)]
data += new_courses
for rec in data:
course_id = rec['id']
defaults = dict(
display_name=rec['display_name'],
org=rec['org'],
display_org_with_default=rec['org'],
number=rec['number'],
created=as_datetime(rec['created']).replace(tzinfo=utc),
enrollment_start=as_datetime(rec['enrollment_start']).replace(tzinfo=utc),
enrollment_end=as_datetime(rec['enrollment_end']).replace(tzinfo=utc),
)
if RELEASE_LINE != 'ginkgo':
defaults['version'] = CourseOverview.VERSION
CourseOverview.objects.update_or_create(
id=as_course_key(course_id),
defaults=defaults,
)
示例2: seed_course_completions
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def seed_course_completions():
"""
go over the dates
"""
for co in CourseOverview.objects.all():
# Note there is a performance hit for using '?'
qs = CourseEnrollment.objects.filter(course_id=co.id)
# we just want a few of the enrollments to have completed
# first cut, have 25% of learners complete course
sample = int(qs.count() * 0.25)
for ce in qs.order_by('?')[:sample]:
GeneratedCertificate.objects.create(
user=ce.user,
course_id=co.id,
created_date=as_datetime(FAKE.date_between(
ce.created, LAST_DAY)).replace(tzinfo=utc),
)
示例3: test_certificate_and_completion
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def test_certificate_and_completion(self):
'''
We're testing both certificate completion because currently, the only
way to tell if a user
'''
# We shouldn't have any certificates for this
# course enrollment
assert not self.lcg.certificates()
assert not self.lcg.learner_completed()
# Create a certificate record for this user
expected_cert = GeneratedCertificateFactory(
user=self.lcg.learner,
course_id=self.lcg.course.id,
created_date=datetime.datetime(2018, 6, 1, tzinfo=utc))
assert expected_cert
check_certs = self.lcg.certificates()
assert check_certs.count() == 1
assert check_certs[0] == expected_cert
assert self.lcg.learner_completed()
示例4: setup
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def setup(self, db):
self.site = SiteFactory()
self.date_1 = datetime(2020, 2, 2, tzinfo=utc)
self.date_2 = self.date_1 + relativedelta(months=1) # future of date_1
self.course_enrollment = CourseEnrollmentFactory()
self.student_modules = [
StudentModuleFactory(student=self.course_enrollment.user,
course_id=self.course_enrollment.course_id,
modified=self.date_1),
StudentModuleFactory(student=self.course_enrollment.user,
course_id=self.course_enrollment.course_id,
modified=self.date_2)]
self.progress_data = dict(points_possible=100,
points_earned=25,
sections_worked=4,
count=5)
示例5: smm_test_data
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def smm_test_data(db):
"""
Minimal test data for very simple test case
"""
site = SiteFactory()
mock_today = datetime(year=2020, month=2, day=1, tzinfo=utc)
last_month = mock_today - relativedelta(months=1)
month_before = last_month - relativedelta(months=1)
month_before_sm = [StudentModuleFactory(created=month_before,
modified=month_before)]
last_month_sm = [StudentModuleFactory(created=last_month,
modified=last_month) for i in range(2)]
return dict(site=site,
mock_today=mock_today,
last_month=last_month,
month_before=month_before,
last_month_sm=last_month_sm,
month_before_sm=month_before_sm)
示例6: as_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def as_datetime(val):
'''
TODO: Add arg flag to say if caller wants end of day, beginning of day
or a particular time of day if the param is a datetime.date obj
'''
if isinstance(val, datetime.datetime):
return val
elif isinstance(val, datetime.date):
# Return the end of the day, set timezone to be UTC
return datetime.datetime(
year=val.year,
month=val.month,
day=val.day,
).replace(tzinfo=utc)
elif isinstance(val, basestring): # noqa: F821
return dateutil_parse(val).replace(tzinfo=utc)
else:
raise TypeError(
'value of type "{}" cannot be converted to a datetime object'.format(
type(val)))
示例7: backfill_monthly_metrics_for_site
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def backfill_monthly_metrics_for_site(site, overwrite=False):
"""Backfill all historical site metrics for the specified site
"""
site_sm = get_student_modules_for_site(site)
if not site_sm:
return None
first_created = site_sm.order_by('created').first().created
start_month = datetime(year=first_created.year,
month=first_created.month,
day=1,
tzinfo=utc)
last_month = datetime.utcnow().replace(tzinfo=utc) - relativedelta(months=1)
backfilled = []
for dt in rrule(freq=MONTHLY, dtstart=start_month, until=last_month):
obj, created = fill_month(site=site,
month_for=dt,
student_modules=site_sm,
overwrite=overwrite)
backfilled.append(dict(obj=obj, created=created, dt=dt))
return backfilled
示例8: value_to_db_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [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)
示例9: value_to_db_datetime
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [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)
示例10: adapt_datetime_with_timezone_support
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
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.
示例11: handle
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [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)
示例12: test_localize
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def test_localize(self):
env = Environment(extensions=[DjangoL10n])
template = env.from_string("{{ foo }}")
context1 = {'foo': 1.23}
date = datetime.datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc)
context2 = {'foo': date}
translation.activate('en')
self.assertEqual('1.23', template.render(context1))
translation.activate('de')
self.assertEqual('1,23', template.render(context1))
translation.activate('es')
timezone.activate('America/Argentina/Buenos_Aires')
self.assertEqual('1 de Octubre de 2000 a las 11:10', template.render(context2))
timezone.activate('Europe/Berlin')
self.assertEqual('1 de Octubre de 2000 a las 16:10', template.render(context2))
translation.activate('de')
self.assertEqual('1. Oktober 2000 16:10', template.render(context2))
timezone.activate('America/Argentina/Buenos_Aires')
self.assertEqual('1. Oktober 2000 11:10', template.render(context2))
示例13: latest_post_date
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def latest_post_date(self):
"""
Return the latest item's pubdate or updateddate. If no items
have either of these attributes this return the current UTC date/time.
"""
latest_date = None
date_keys = ('updateddate', 'pubdate')
for item in self.items:
for date_key in date_keys:
item_date = item.get(date_key)
if item_date:
if latest_date is None or item_date > latest_date:
latest_date = item_date
# datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now
return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc)
示例14: seed_users
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def seed_users(data=None):
if not data:
data = cans.USER_DATA
first_date = days_from(LAST_DAY, DAYS_BACK * -1)
created_users = []
for rec in data:
try:
profile_rec = rec.get('profile', None)
user = get_user_model().objects.create_user(
username=rec['username'],
password=rec['password'],
email=rec['email'],
)
user.is_staff = rec.get('is_staff', False)
user.is_superuser = rec.get('is_superuser', False)
user.date_joined = as_datetime(
FAKE.date_between(first_date, LAST_DAY)).replace(tzinfo=utc)
user.save()
created_users.append(user)
if profile_rec:
UserProfile.objects.create(
user=user,
name=profile_rec['fullname'],
gender=profile_rec.get('gender', None),
country=profile_rec.get('country', None),
)
except IntegrityError as e:
print('skipping duplicate user email {}'.format(e))
return created_users
示例15: seed_course_enrollments_for_course
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import utc [as 别名]
def seed_course_enrollments_for_course(course_id, users, max_days_back):
def enroll_date(max_days_back):
days_back = random.randint(1, abs(max_days_back))
return days_from(LAST_DAY, days_back * -1)
for user in users:
if VERBOSE:
print('seeding course enrollment for user {}'.format(user.username))
CourseEnrollment.objects.update_or_create(
course_id=course_id,
user=user,
created=as_datetime(enroll_date(max_days_back)).replace(tzinfo=utc),
)