def comment(request,id):
if id:
r = Restaurant.objects.get(id=id)
else:
return HttpResponseRedirect("/restaurants_list/")
if request.POST:
visitor = request.POST['visitor']
content = request.POST['content']
email = request.POST['email']
date_time = timezone.localtime(timezone.now())
#??for database
Comment.objects.create(
visitor = visitor,
email = email,
content = content,
date_time = date_time,
restaurant = r
)
return render_to_response('comments.html',RequestContext(request,locals()))
python类localtime()的实例源码
def comment(request,id):
if id:
r = Restaurant.objects.get(id=id)
else:
return HttpResponseRedirect("/restaurants_list/")
if request.POST:
visitor = request.POST['visitor']
content = request.POST['content']
email = request.POST['email']
date_time = timezone.localtime(timezone.now())
#??for database
Comment.objects.create(
visitor = visitor,
email = email,
content = content,
date_time = date_time,
restaurant = r
)
return render_to_response('comments.html',RequestContext(request,locals()))
def html_date(value, displayfmt=None, datetimefmt='c', **kwargs):
"""Format a date and wrap it in a html <time> element.
Additional html attributes may be provided as kwargs (e.g. 'class').
Note: Converts the value to localtime as we loose the expects_localtime
flag functionality by directly calling the date filter from django.
"""
localtime_value = timezone.localtime(value)
displaydate = defaultfilters.date(localtime_value, displayfmt)
datetime = defaultfilters.date(localtime_value, datetimefmt)
attribs = flatatt(kwargs)
result = '<time %s datetime="%s">%s</time>' % (attribs,
datetime,
displaydate)
return mark_safe(result)
def test_set_next_notification_date(self, now_mock):
""" Notifications: Test if next notification date is set """
now_mock.return_value = timezone.make_aware(
timezone.datetime(2016, 11, 16))
now = timezone.localtime(timezone.now())
tomorrow = (timezone.localtime(timezone.now()) +
timezone.timedelta(hours=24)).date()
settings = NotificationSetting.get_solo()
settings.next_notification = now
settings.save()
dsmr_notification.services.set_next_notification(settings, now)
self.assertEqual(settings.next_notification, tomorrow)
def test_notification_api_fail(self, now_mock, requests_post_mock):
""" Notifications: Test API failure for notify() """
now_mock.return_value = timezone.make_aware(
timezone.datetime(2016, 11, 17, hour=0, minute=5))
requests_post_mock.return_value = mock.MagicMock(
status_code=403, text='Forbidden')
settings = NotificationSetting.get_solo()
settings.send_notification = True
settings.notification_service = NotificationSetting.NOTIFICATION_NMA
settings.api_key = 'es7sh2d-DSMR-Reader-Rulez-iweu732'
settings.next_notification = timezone.localtime(timezone.now())
settings.save()
if self.fixtures:
with self.assertRaises(AssertionError):
dsmr_notification.services.notify()
else:
# When having no data, this should NOT raise an exception.
return dsmr_notification.services.notify()
with self.assertRaisesMessage(
AssertionError, 'Notify API call failed: Forbidden (HTTP403)'):
dsmr_notification.services.notify()
def test_check_interval_restriction(self, now_mock, create_backup_mock):
""" Test whether backups are restricted by one backup per day. """
now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1, hour=1, minute=5))
# Fake latest backup.
now = timezone.localtime(timezone.now())
backup_settings = BackupSettings.get_solo()
backup_settings.latest_backup = now
backup_settings.backup_time = (now - timezone.timedelta(minutes=1)).time()
backup_settings.save()
self.assertIsNotNone(BackupSettings.get_solo().latest_backup)
self.assertFalse(create_backup_mock.called)
# Should not do anything.
dsmr_backup.services.backup.check()
self.assertFalse(create_backup_mock.called)
backup_settings.latest_backup = now - timezone.timedelta(days=1)
backup_settings.save()
# Should be fine to backup now.
dsmr_backup.services.backup.check()
self.assertTrue(create_backup_mock.called)
def test_check_backup_time_restriction(self, now_mock, create_backup_mock):
""" Test whether backups are restricted by user's backup time preference. """
now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1, hour=1, minute=5))
now = timezone.localtime(timezone.now())
backup_settings = BackupSettings.get_solo()
backup_settings.latest_backup = now - timezone.timedelta(days=1)
backup_settings.backup_time = (now + timezone.timedelta(seconds=15)).time()
backup_settings.save()
# Should not do anything, we should backup a minute from now.
self.assertFalse(create_backup_mock.called)
dsmr_backup.services.backup.check()
self.assertFalse(create_backup_mock.called)
# Should be fine to backup now. Passed prefered time of user.
backup_settings.backup_time = now.time()
backup_settings.save()
dsmr_backup.services.backup.check()
self.assertTrue(create_backup_mock.called)
def check():
""" Checks whether a new backup should be created. Creates one if needed as well. """
backup_settings = BackupSettings.get_solo()
# Skip when backups disabled.
if not backup_settings.daily_backup:
return
# Postpone when we already created a backup today.
if backup_settings.latest_backup and backup_settings.latest_backup.date() == timezone.now().date():
return
# Timezone magic to make sure we select and combine the CURRENT day, in the user's timezone.
next_backup_timestamp = timezone.make_aware(timezone.datetime.combine(
timezone.localtime(timezone.now()), backup_settings.backup_time
))
if backup_settings.latest_backup and timezone.now() < next_backup_timestamp:
# Postpone when the user's backup time preference has not been passed yet.
return
# For backend logging in Supervisor.
print(' - Creating new backup.')
create()
def get_context_data(self, **kwargs):
context_data = super(Statistics, self).get_context_data(**kwargs)
context_data['capabilities'] = dsmr_backend.services.get_capabilities()
try:
context_data['latest_reading'] = DsmrReading.objects.all().order_by('-pk')[0]
except IndexError:
pass
today = timezone.localtime(timezone.now()).date()
context_data['datalogger_settings'] = DataloggerSettings.get_solo()
context_data['meter_statistics'] = MeterStatistics.get_solo()
try:
context_data['energy_prices'] = EnergySupplierPrice.objects.by_date(today)
except EnergySupplierPrice.DoesNotExist:
pass
return context_data
def __init__(self, datetime, part, tz):
self.datetime = localtime(datetime, tz)
self.part = part
def __str__(self):
start = localtime(self.time_start).replace(tzinfo=None)
if self.time_end is None:
return "%s -> (%s)" % (start, self.registration_number)
if self.time_start.date() == self.time_end.date():
end = localtime(self.time_end).time().replace(tzinfo=None)
else:
end = localtime(self.time_end).replace(tzinfo=None)
return "%s -> %s (%s)" % (start, end, self.registration_number)
def _sqlite_datetime_parse(dt, tzname):
if dt is None:
return None
try:
dt = backend_utils.typecast_timestamp(dt)
except (ValueError, TypeError):
return None
if tzname is not None:
dt = timezone.localtime(dt, pytz.timezone(tzname))
return dt
def timezone_today():
"""
Return the current date in the current time zone.
"""
if settings.USE_TZ:
return timezone.localtime(timezone.now()).date()
else:
return datetime.date.today()
def localtime(value):
"""
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone())
def limit_candidate_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"dataentry": "manual", "electiondate__gte": time_offset}
def limit_election_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"electiondate__gte": time_offset}
def limit_race_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"dataentry": "manual", "electiondate__gte": time_offset}
## election_fk was removed bc it now pulls that info from the race_fk, but then added back and not exposed bc of a resultmanual error on test server
def limit_race_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"dataentry": "manual", "electiondate__gte": time_offset}
def limit_candidate_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"dataentry": "manual", "electiondate__gte": time_offset}
def limit_reportingunit_choices():
today = timezone.localtime(timezone.now()).date()
time_offset = today - timedelta(days=60)
return {"electiondate__gte": time_offset}