当前位置: 首页>>代码示例>>Python>>正文


Python dateparse.parse_datetime方法代码示例

本文整理汇总了Python中django.utils.dateparse.parse_datetime方法的典型用法代码示例。如果您正苦于以下问题:Python dateparse.parse_datetime方法的具体用法?Python dateparse.parse_datetime怎么用?Python dateparse.parse_datetime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.dateparse的用法示例。


在下文中一共展示了dateparse.parse_datetime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [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) 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:26,代码来源:sync_deleted_instances_fix.py

示例2: transform_alarm_history

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def transform_alarm_history(results, name, ts_mode, ts_offset):
    new_list = []

    def get_ts_val(val):
        if ts_mode == 'bl':
            offset = int((ts_offset or '0').replace('+', ''))
            dt_val = parse_datetime(val) + timedelta(hours=offset)
            dt_val_formatter = dt_val.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            return dt_val_formatter.replace('000Z', '')
        elif ts_mode != 'utc':
            raise ValueError('%s is not supported timestamp format' % ts_mode)
        else:
            return val  # utc case

    for item in results:
        new_list.append({'alarm_id': item['alarm_id'],
                         'name': name,
                         'old_state': item['old_state'],
                         'new_state': item['new_state'],
                         'timestamp': get_ts_val(item['timestamp']),
                         'reason': item['reason'],
                         'metrics': item['metrics'],
                         'reason_data': item['reason_data']})
    return new_list 
开发者ID:openstack,项目名称:monasca-ui,代码行数:26,代码来源:views.py

示例3: history

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def history(self, page):
        GIT_COMMIT_FIELDS = ['commit', 'author', 'date', 'date_relative', 'date_parsed', 'message']
        GIT_LOG_FORMAT = '%x1f'.join(['%h', '%an', '%ad', '%ar', '%ai', '%s']) + '%x1e'
        output = git.log('--format=%s' % GIT_LOG_FORMAT, '--follow', '-z', '--shortstat', page.abspath)
        output = output.split('\n')
        history = []
        for line in output:
            if '\x1f' in line:
                log = line.strip('\x1e\x00').split('\x1f')
                history.append(dict(zip(GIT_COMMIT_FIELDS, log)))
            else:
                insertion = re.match(r'.* (\d+) insertion', line)
                deletion = re.match(r'.* (\d+) deletion', line)
                history[-1]['insertion'] = int(insertion.group(1)) if insertion else 0
                history[-1]['deletion'] = int(deletion.group(1)) if deletion else 0

        max_changes = float(max([(v['insertion'] + v['deletion']) for v in history])) or 1.0
        for v in history:
            v.update({'insertion_relative': str((v['insertion'] / max_changes) * 100),
                      'deletion_relative': str((v['deletion'] / max_changes) * 100),
                      'date_parsed': parse_datetime('%s %s%s' % tuple(v['date_parsed'].split()))})
        return history 
开发者ID:mgaitan,项目名称:waliki,代码行数:24,代码来源:models.py

示例4: get_task_run_length

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def get_task_run_length(self, task_type):
        """Returns the run time length for the given task type, possibly None

        :param task_type: The task type
        :type task_type: string
        :returns: The task run time length
        :rtype: :class:`datetime.timedelta`:
        """

        for task_dict in self._task_results['tasks']:
            if task_dict['type'] == task_type:
                if 'started' in task_dict and 'ended' in task_dict:
                    started = dateparse.parse_datetime(task_dict['started'])
                    ended = dateparse.parse_datetime(task_dict['ended'])
                    return ended - started
        return None 
开发者ID:ngageoint,项目名称:scale,代码行数:18,代码来源:task_results.py

示例5: get_v6

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def get_v6(self, request):
        """The v6 version to get high level status information

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        status_dict = Scheduler.objects.get_master().status

        if not status_dict:  # Empty dict from model initialization
            raise ServiceUnavailable(unicode('Status is missing. Scheduler may be down.'))

        # If status dict has not been updated recently, assume scheduler is down or slow
        status_timestamp = parse_datetime(status_dict['timestamp'])
        if (now() - status_timestamp).total_seconds() > StatusView.STATUS_FRESHNESS_THRESHOLD:
            raise ServiceUnavailable(unicode('Status is over %d seconds old' % StatusView.STATUS_FRESHNESS_THRESHOLD))

        return Response(status_dict) 
开发者ID:ngageoint,项目名称:scale,代码行数:22,代码来源:views.py

示例6: datetime_validator

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [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 
开发者ID:anyant,项目名称:rssant,代码行数:25,代码来源:validator.py

示例7: sanitize_field_value

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def sanitize_field_value(cls, field_name, value):
        if field_name == 'value':
            return float(value)
        if field_name == 'timestamp':
            from django.db import models
            if value == None:
                return timezone.now()
            timestamp = parse_datetime(value)
            if timezone.is_aware(timestamp):
                return timestamp
            return timezone.make_aware(timestamp, timezone.get_current_timezone())


    # we store the metric as a tag in Influx for convenience of querying
    # for clients that are using influx directly. It's not a real field that's
    # handled by Chain 
开发者ID:ResEnv,项目名称:chain-api,代码行数:18,代码来源:resources.py

示例8: __init__

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def __init__(self, manifest, manifest_url):
        dict.__init__(self)

        self['manifest'] = manifest
        self['manifest_url'] = manifest_url
        self['uuid'] = manifest['uuid']
        self['name'] = manifest['name']
        self['version'] = manifest.get('version', '')
        self['created'] = parse_datetime(manifest.get('published_at', '')) or ''
        self['ostype'] = Image.os_to_ostype(manifest)
        self['desc'] = manifest.get('description', '')
        self['homepage'] = manifest.get('homepage')
        self['size'] = manifest.get('image_size', Image.DEFAULT_SIZE)
        self['state'] = manifest.get('state', '')

        try:
            self['download_size'] = manifest['files'][0]['size']
        except (KeyError, IndexError):
            self['download_size'] = 0 
开发者ID:erigones,项目名称:esdc-ce,代码行数:21,代码来源:imagestore.py

示例9: test_discovery_sheet

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def test_discovery_sheet(self, mock_timezone):
        non_project_url = reverse(discovery_sheet, args=[NON_PROJECT_GUID])
        self.check_staff_login(non_project_url)

        mock_timezone.now.return_value = pytz.timezone("US/Eastern").localize(parse_datetime("2020-04-27 20:16:01"), is_dst=None)
        response = self.client.get(non_project_url)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Invalid project {}'.format(NON_PROJECT_GUID))
        response_json = response.json()
        self.assertEqual(response_json['error'], 'Invalid project {}'.format(NON_PROJECT_GUID))

        empty_project_url = reverse(discovery_sheet, args=[PROJECT_EMPTY_GUID])

        response = self.client.get(empty_project_url)
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertListEqual(response_json.keys(), ['rows', 'errors'])
        self.assertListEqual(response_json['rows'], [])
        self.assertListEqual(response_json['errors'], ["No data loaded for project: Empty Project"])

        url = reverse(discovery_sheet, args=[PROJECT_GUID])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertListEqual(response_json.keys(), ['rows', 'errors'])
        self.assertListEqual(response_json['errors'], [u'No data loaded for family: no_individuals. Skipping...'])
        self.assertEqual(len(response_json['rows']), 10)
        self.assertIn(EXPECTED_DISCOVERY_SHEET_ROW, response_json['rows'])

        # test compound het reporting
        url = reverse(discovery_sheet, args=[COMPOUND_HET_PROJECT_GUID])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertListEqual(response_json.keys(), ['rows', 'errors'])
        self.assertListEqual(response_json['errors'], ['HPO category field not set for some HPO terms in 11'])
        self.assertEqual(len(response_json['rows']), 2)
        self.assertIn(EXPECTED_DISCOVERY_SHEET_COMPOUND_HET_ROW, response_json['rows']) 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:40,代码来源:staff_api_tests.py

示例10: parse_datetime_with_timezone_support

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def parse_datetime_with_timezone_support(value):
    dt = parse_datetime(value)
    # Confirm that dt is naive before overwriting its tzinfo.
    if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
        dt = dt.replace(tzinfo=timezone.utc)
    return dt 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:8,代码来源:utils.py

示例11: get_queryset

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def get_queryset(self):
        from_date = self.request.query_params.get('fromDate')
        to_date = self.request.query_params.get('toDate')
        from_date = parse_datetime(from_date) if from_date else timezone.now() - datetime.timedelta(days=30)
        to_date = parse_datetime(to_date) if to_date else timezone.now()
        return GasPrice.objects.filter(created__range=[from_date, to_date]).order_by('created') 
开发者ID:gnosis,项目名称:safe-relay-service,代码行数:8,代码来源:views.py

示例12: get

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def get(self, request, format=None):
        """
        Get stats of the Safe Relay Service
        """
        from_date = self.request.query_params.get('fromDate')
        to_date = self.request.query_params.get('toDate')
        from_date = parse_datetime(from_date) if from_date else from_date
        to_date = parse_datetime(to_date) if to_date else to_date
        return Response(status=status.HTTP_200_OK, data=StatsServiceProvider().get_relay_stats(from_date, to_date)) 
开发者ID:gnosis,项目名称:safe-relay-service,代码行数:11,代码来源:views.py

示例13: setUp

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def setUp(self):
        self._create_user_and_login()
        self.fixture_dir = os.path.join(
            self.this_directory, 'fixtures', 'csv_export')
        self._submission_time = parse_datetime('2013-02-18 15:54:01Z') 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:7,代码来源:test_csv_export.py

示例14: setUp

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def setUp(self):
        super(TestExports, self).setUp()
        self._submission_time = parse_datetime('2013-02-18 15:54:01Z') 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:5,代码来源:test_exports.py

示例15: setUp

# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_datetime [as 别名]
def setUp(self):
        self._create_user_and_login()
        self._submission_time = parse_datetime('2013-02-18 15:54:01Z') 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:5,代码来源:test_pandas_mongo_bridge.py


注:本文中的django.utils.dateparse.parse_datetime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。