Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def parse_isotime(timestr):
"""Parse time from ISO 8601 format."""
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(six.text_type(e))
except TypeError as e:
raise ValueError(six.text_type(e))
def get_times(request):
"""Gets start and endtime from request
As we use no timezone in NAV, remove it from parsed timestamps
:param request: django.http.HttpRequest
"""
starttime = request.GET.get('starttime')
endtime = request.GET.get('endtime')
try:
if starttime:
starttime = iso8601.parse_date(starttime).replace(tzinfo=None)
if endtime:
endtime = iso8601.parse_date(endtime).replace(tzinfo=None)
except iso8601.ParseError:
raise Iso8601ParseError
return starttime, endtime
"""
Goes through a parsed XML document and recursively pulls out any ledger XML blocks.
"""
for child in node:
if child.tag in commtrack_node_names:
yield child
else:
for e in _extract_ledger_nodes_from_xml(child):
yield e
for elem in _extract_ledger_nodes_from_xml(form_xml):
report_type, ledger_json = convert_xml_to_json(elem, last_xmlns=COMMTRACK_REPORT_XMLNS)
if ledger_json.get('@date'):
try:
ledger_json['@date'] = adjust_text_to_datetime(ledger_json['@date'])
except iso8601.ParseError:
pass
yield _ledger_json_to_stock_report_helper(xform, report_type, ledger_json)
def is_iso_time(iso):
"""
Returns True if provided time can be parsed in iso format
to a datetime tuple
"""
try:
iso_to_datetime_tuple(iso)
return True
except iso8601.ParseError:
return False
to force timezone processing, it can be called as follows
>>> from corehq.apps.tzmigration.api import force_phone_timezones_should_be_processed
>>> with force_phone_timezones_should_be_processed():
>>> adjust_datetimes(form_json)
"""
process_timezones = process_timezones or phone_timezones_should_be_processed()
# this strips the timezone like we've always done
# todo: in the future this will convert to UTC
if isinstance(data, six.string_types) and jsonobject.re_loose_datetime.match(data):
try:
parent[key] = six.text_type(json_format_datetime(
adjust_text_to_datetime(data, process_timezones=process_timezones)
))
except iso8601.ParseError:
pass
elif isinstance(data, dict):
for key, value in data.items():
adjust_datetimes(value, parent=data, key=key, process_timezones=process_timezones)
elif isinstance(data, list):
for i, value in enumerate(data):
adjust_datetimes(value, parent=data, key=i, process_timezones=process_timezones)
# return data, just for convenience in testing
# this is the original input, modified, not a new data structure
return data
def parseUploadTime(timeStr):
try:
# format used by GeoCam Mobile 2009
return parseCsvTime(timeStr)
except ValueError:
pass
try:
# ISO 8601 format we should probably use in the future
return iso8601.parse_date(timeStr)
except iso8601.ParseError:
pass
try:
# POSIX time stamp may be easier to produce for some clients
posixTimeStamp = float(timeStr)
except ValueError:
pass
else:
return datetime.datetime.fromtimestamp(posixTimeStamp)
# hm, nothing worked
raise ValueError('could not parse datetime from %s' % timeStr)
def parse_isotime(timestr):
"""Parse time from ISO 8601 format"""
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(e.message)
except TypeError as e:
raise ValueError(e.message)
def parse_iso_datetime(value):
# Prevent iso8601 over-zealous datetime parsing
if '-' in value and ':' in value:
try:
value = iso8601.parse_date(value)
except iso8601.ParseError:
pass
return value
def custom_validate(self, value):
if isinstance(value, datetime):
return
try:
iso8601.parse_date(value)
return
except iso8601.ParseError:
pass
raise ValidationError("Timestamp field expects a datetime or an "
"iso8601 formatted string.")
try:
payload = json.loads(message.payload.decode("utf-8"))
except ValueError as e:
raise InvalidEventException("Unable to parse JSON. payload=\"%s\" error=%s" % (message.payload, str(e)))
data = None
timestamp = None
# Try to parse a timestamp
try:
if 'ts' in payload:
dt = iso8601.parse_date(payload['ts'])
timestamp = dt.astimezone(pytz.timezone('UTC'))
else:
timestamp = datetime.now(pytz.timezone('UTC'))
except iso8601.ParseError as e:
raise InvalidEventException("Unable to parse event timestamp: %s" % str(e))
# Try to parse the data
if 'd' in payload:
data = payload['d']
# TODO: Flatten JSON, covert into array of key/value pairs
return Message(data, timestamp)