本文整理汇总了Python中corehq.util.timezones.conversions.ServerTime类的典型用法代码示例。如果您正苦于以下问题:Python ServerTime类的具体用法?Python ServerTime怎么用?Python ServerTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ServerTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: should_sync
def should_sync(domain, last_sync, utcnow=None):
# definitely sync if we haven't synced before
if not last_sync or not last_sync.date:
return True
# utcnow only used in tests to mock other times
utcnow = utcnow or datetime.utcnow()
try:
timezone = domain.get_default_timezone()
except pytz.UnknownTimeZoneError:
timezone = utc
_assert = soft_assert(to=['droberts' + '@' + 'dimagi.com'])
last_sync_utc = last_sync.date
if not _assert(last_sync_utc.tzinfo is None,
'last_sync.date should be an offset-naive dt'):
last_sync_utc = UserTime(last_sync_utc).server_time().done()
# check if user has already synced today (in local timezone).
# Indicators only change daily.
last_sync_local = ServerTime(last_sync_utc).user_time(timezone).done()
current_date_local = ServerTime(utcnow).user_time(timezone).done()
if current_date_local.date() != last_sync_local.date():
return True
return False
示例2: submission_or_completion_time
def submission_or_completion_time(self):
time = iso_string_to_datetime(safe_index(self.form, self.report.time_field.split('.')))
if self.report.by_submission_time:
user_time = ServerTime(time).user_time(self.report.timezone)
else:
user_time = PhoneTime(time, self.report.timezone).user_time(self.report.timezone)
return user_time.ui_string(USER_DATETIME_FORMAT_WITH_SEC)
示例3: template_context
def template_context(self):
event = self.messaging_event
date = ServerTime(event.date).user_time(self.timezone).done()
return {
'messaging_event_date': date.strftime(SERVER_DATETIME_FORMAT),
'messaging_event_type': self.get_source_display(event, display_only=True),
}
示例4: test_server_to_user
def test_server_to_user(self):
cases = [
('2015-03-20T12:00:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T08:00:00-04:00'),
('2015-03-21T00:30:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T20:30:00-04:00'),
]
for in_, tz, out in cases:
server_dt = dateutil.parser.parse(in_)
user_dt = ServerTime(server_dt).user_time(tz).done()
self.assertEqual(user_dt.isoformat(), out)
示例5: test_server_to_phone
def test_server_to_phone(self):
cases = [
('2015-03-20T12:00:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T08:00:00'),
('2015-03-21T00:30:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T20:30:00'),
]
for in_, tz, out in cases:
server_dt = dateutil.parser.parse(in_)
if get_timezone_data_migration_complete():
phone_dt = server_dt
else:
phone_dt = ServerTime(server_dt).phone_time(tz).done()
self.assertEqual(phone_dt.isoformat(), out)
示例6: test_server_to_phone
def test_server_to_phone(self):
cases = [
('2015-03-20T12:00:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T08:00:00'),
('2015-03-21T00:30:00', pytz.FixedOffset(-4 * 60),
'2015-03-20T20:30:00'),
]
for in_, tz, out in cases:
server_dt = dateutil.parser.parse(in_)
phone_dt = ServerTime(server_dt).phone_time(tz).done()
if phone_timezones_have_been_processed():
# no change
self.assertEqual(phone_dt.isoformat(), in_)
else:
self.assertEqual(phone_dt.isoformat(), out)
示例7: _update_tech_issue_for_escalation
def _update_tech_issue_for_escalation(case, escalated_ticket_level):
today = ServerTime(datetime.utcnow()).user_time(pytz.timezone('Asia/Kolkata')).done().date()
return update_case(
case.domain,
case.case_id,
case_properties={
'ticket_level': escalated_ticket_level,
'change_in_level': '1',
'touch_case_date': today.strftime('%Y-%m-%d'),
},
close=False,
xmlns=AUTO_UPDATE_XMLNS,
device_id=__name__ + "._update_tech_issue_for_escalation",
)
示例8: check_obs_props
def check_obs_props(obs, props):
for k, v in props.items():
if k.endswith("_date"):
# datetime check
obs_datetime = getattr(obs, k)
val_datetime = dateutil.parser.parse(v)
if k in ('completed_date', 'created_date'):
obs_datetime = ServerTime(obs_datetime).user_time(PACT_TIMEZONE).done()
obs_date = obs_datetime.date()
val_date = val_datetime.date()
self.assertEquals(obs_date, val_date)
else:
self.assertEquals(getattr(obs, k), v,
msg="Error, observation %s\n\t%s didn't match: %s != %s" % (
json.dumps(obs.to_json(), indent=4), k, getattr(obs, k),
v))
示例9: midnights
def midnights(self, utcnow=None):
"""Returns a list containing two datetimes in UTC that corresponds to midnight
in the domains timezone on either side of the current UTC datetime.
i.e. [<previous midnight in TZ>, <next midnight in TZ>]
>>> d = DomainLite('', 'Asia/Kolkata', '', True)
>>> d.midnights(datetime(2015, 8, 27, 18, 30, 0 ))
[datetime.datetime(2015, 8, 26, 18, 30), datetime.datetime(2015, 8, 27, 18, 30)]
>>> d.midnights(datetime(2015, 8, 27, 18, 31, 0 ))
[datetime.datetime(2015, 8, 27, 18, 30), datetime.datetime(2015, 8, 28, 18, 30)]
"""
utcnow = utcnow or datetime.utcnow()
tz = pytz.timezone(self.default_timezone)
current_time_tz = ServerTime(utcnow).user_time(tz).done()
midnight_tz1 = current_time_tz.replace(hour=0, minute=0, second=0, microsecond=0)
midnight_tz_utc1 = UserTime(midnight_tz1).server_time().done()
midnight_tz_utc2 = midnight_tz_utc1 + timedelta(days=(1 if midnight_tz_utc1 < utcnow else -1))
return sorted([midnight_tz_utc1, midnight_tz_utc2])
示例10: rows
def rows(self):
def form_data_link(instance_id):
return "<a class='ajax_dialog' target='_new' href='%(url)s'>%(text)s</a>" % {
"url": absolute_reverse('render_form_data', args=[self.domain, instance_id]),
"text": _("View Form")
}
submissions = [res['_source'] for res in self.es_results.get('hits', {}).get('hits', [])]
for form in submissions:
uid = form["form"]["meta"]["userID"]
username = form["form"]["meta"].get("username")
try:
if username not in ['demo_user', 'admin']:
full_name = get_cached_property(CouchUser, uid, 'full_name', expiry=7*24*60*60)
name = '"%s"' % full_name if full_name else ""
else:
name = ""
except (ResourceNotFound, IncompatibleDocument):
name = "<b>[unregistered]</b>"
time = iso_string_to_datetime(safe_index(form, self.time_field.split('.')))
if self.by_submission_time:
user_time = ServerTime(time).user_time(self.timezone)
else:
user_time = PhoneTime(time, self.timezone).user_time(self.timezone)
init_cells = [
form_data_link(form["_id"]),
(username or _('No data for username')) + (" %s" % name if name else ""),
user_time.ui_string(USER_DATETIME_FORMAT_WITH_SEC),
xmlns_to_name(self.domain, form.get("xmlns"), app_id=form.get("app_id")),
]
def cell(field):
return form["form"].get(field)
init_cells.extend([cell(field) for field in self.other_fields])
yield init_cells
示例11: broadcast_form
def broadcast_form(self):
if self.request.method == "POST":
return self.form_class(self.request.POST, **self.form_kwargs)
broadcast = self.broadcast
start_user_time = ServerTime(broadcast.start_datetime).user_time(self.project_timezone)
initial = {
"timing": SEND_LATER,
"date": start_user_time.ui_string("%Y-%m-%d"),
"time": start_user_time.ui_string("%H:%M"),
"recipient_type": broadcast.recipient,
"case_group_id": broadcast.sample_id,
"user_group_id": broadcast.user_group_id,
"content_type": broadcast.method,
"message": broadcast.events[0].message.get(broadcast.default_lang, None),
"subject": broadcast.events[0].subject.get(broadcast.default_lang, None),
"form_unique_id": broadcast.events[0].form_unique_id,
"location_ids": ",".join(broadcast.location_ids),
"include_child_locations": broadcast.include_child_locations,
}
if toggles.EWS_BROADCAST_BY_ROLE.enabled(self.domain):
initial["role"] = broadcast.user_data_filter.get("role", [None])[0]
return self.form_class(initial=initial, **self.form_kwargs)
示例12: should_sync
def should_sync(domain, last_sync, utcnow=None):
# definitely sync if we haven't synced before
if not last_sync or not last_sync.date:
return True
# utcnow only used in tests to mock other times
utcnow = utcnow or datetime.utcnow()
try:
timezone = domain.get_default_timezone()
except pytz.UnknownTimeZoneError:
timezone = utc
last_sync_utc = last_sync.date
# check if user has already synced today (in local timezone).
# Indicators only change daily.
last_sync_local = ServerTime(last_sync_utc).user_time(timezone).done()
current_date_local = ServerTime(utcnow).user_time(timezone).done()
if current_date_local.date() != last_sync_local.date():
return True
return False
示例13: __init__
def __init__(self, domain_object=None):
self.domain_object = domain_object
if domain_object:
self.date = ServerTime(datetime.utcnow()).user_time(domain_object.get_default_timezone()).done().date()
else:
self.date = datetime.utcnow().date()
self.key = 'outbound-daily-count-for-%s-%s' % (
domain_object.name if domain_object else '',
self.date.strftime('%Y-%m-%d')
)
# We need access to the raw redis client because calling incr on
# a django_redis RedisCache object raises an error if the key
# doesn't exist.
self.client = get_redis_client().client.get_client()
示例14: format_broadcast_name
def format_broadcast_name(self, broadcast):
user_time = ServerTime(broadcast.start_datetime).user_time(self.project_timezone)
return user_time.ui_string(SERVER_DATETIME_FORMAT)
示例15: test_ui_string
def test_ui_string(self):
now = datetime.datetime.utcnow()
user_time = ServerTime(now).user_time(pytz.FixedOffset(-4 * 60))
self.assertEqual(user_time.ui_string(),
user_time.done().strftime(USER_DATETIME_FORMAT))