• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python timeparse.timeparse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pytimeparse.timeparse.timeparse函数的典型用法代码示例。如果您正苦于以下问题:Python timeparse函数的具体用法?Python timeparse怎么用?Python timeparse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: on_trigger

    def on_trigger(self, message):
        """
        @type message: hubbot.message.IRCMessage
        """
        flag = False
        if len(message.parameter_list) == 1:
            try:
                delay = int(message.parameter_list[0])
                flag = True
            except Exception:
                delay = timeparse(message.parameter_list[0])
        else:
            delay = timeparse(" ".join(message.parameter_list))
        if delay is None or delay <= 0:
            return IRCResponse(ResponseType.SAY, "I don't think I understand that...", message.reply_to)
        elif delay > (60 * 60 * 24 * 365):
            return IRCResponse(ResponseType.SAY, "Do you really need a timer that long?", message.reply_to)
        elif delay <= 1:
            return IRCResponse(ResponseType.SAY, "Your timer is up now, {}.".format(message.user.name), message.reply_to)

        else:
            reactor.callLater(delay, self.notify_user, flag, message)
            if flag:
                return IRCResponse(ResponseType.SAY, "{}: A {} second timer has been started!".format(message.user.name, message.parameter_list[0]), message.reply_to)
            else:
                return IRCResponse(ResponseType.SAY, "{}: A {} timer has been started!".format(message.user.name, " ".join(message.parameter_list)), message.reply_to)
开发者ID:HubbeKing,项目名称:Hubbot_Twisted,代码行数:26,代码来源:Timer.py


示例2: _process_json

def _process_json(response_body):
    """
    Returns a UwPassword objects
    """
    data = json.loads(response_body)
    uwpassword = UwPassword(uwnetid=data["uwNetID"],
                            kerb_status=data["kerbStatus"],
                            interval=None,
                            last_change=None,
                            last_change_med=None,
                            expires_med=None,
                            interval_med=None,
                            minimum_length=int(data["minimumLength"]),
                            time_stamp=parse(data["timeStamp"]),)
    if "lastChange" in data:
        uwpassword.last_change = parse(data["lastChange"])

    if "interval" in data:
        uwpassword.interval = timeparse(data["interval"])

    if "lastChangeMed" in data:
        uwpassword.last_change_med = parse(data["lastChangeMed"])

    if "expiresMed" in data:
        uwpassword.expires_med = parse(data["expiresMed"])

    if "intervalMed" in data:
        uwpassword.interval_med = timeparse(data["intervalMed"])

    if "netidStatus" in data:
        netid_status = []
        for status in data["netidStatus"]:
            netid_status.append(status)
        uwpassword.netid_status = netid_status
    return uwpassword
开发者ID:uw-it-aca,项目名称:uw-restclients,代码行数:35,代码来源:password.py


示例3: test_timeparse_14

 def test_timeparse_14(self):
     '''timeparse test case 14.'''
     self.assertEqual(timeparse.timeparse('5 hours, 34 minutes, 56 seconds'),
                      20096)
     self.assertEqual(timeparse.timeparse('+5 hours, 34 minutes, 56 seconds'),
                      20096)
     self.assertEqual(timeparse.timeparse('-5 hours, 34 minutes, 56 seconds'),
                      -20096)
开发者ID:cackovic,项目名称:pytimeparse,代码行数:8,代码来源:testtimeparse.py


示例4: test_timeparse_12

 def test_timeparse_12(self):
     '''timeparse test case 12.'''
     self.assertAlmostEqual(timeparse.timeparse('2 days,  4:13:02.266'),
                            187982.266)
     self.assertAlmostEqual(timeparse.timeparse('+2 days,  4:13:02.266'),
                            187982.266)
     self.assertAlmostEqual(timeparse.timeparse('-2 days,  4:13:02.266'),
                            -187982.266)
开发者ID:cackovic,项目名称:pytimeparse,代码行数:8,代码来源:testtimeparse.py


示例5: test_timeparse_10

 def test_timeparse_10(self):
     '''timeparse test case 10.'''
     self.assertAlmostEqual(timeparse.timeparse('2:04:13:02.266'),
                            187982.266)
     self.assertAlmostEqual(timeparse.timeparse('+2:04:13:02.266'),
                            187982.266)
     self.assertAlmostEqual(timeparse.timeparse('-2:04:13:02.266'),
                            -187982.266)
开发者ID:cackovic,项目名称:pytimeparse,代码行数:8,代码来源:testtimeparse.py


示例6: test_timeparse_16

 def test_timeparse_16(self):
     '''timeparse test case 16.'''
     self.assertEqual(
         timeparse.timeparse('2 days, 5 hours, 34 minutes, 56 seconds'),
         192896)
     self.assertEqual(
         timeparse.timeparse('+2 days, 5 hours, 34 minutes, 56 seconds'),
         192896)
     self.assertEqual(
         timeparse.timeparse('-2 days, 5 hours, 34 minutes, 56 seconds'),
         -192896)
开发者ID:cackovic,项目名称:pytimeparse,代码行数:11,代码来源:testtimeparse.py


示例7: test_timeparse_multipliers

 def test_timeparse_multipliers(self):
     '''Test parsing time unit multipliers.'''
     self.assertEqual(timeparse.timeparse('32 min'),
                      1920)
     self.assertEqual(timeparse.timeparse('1 min'),
                      60)
     self.assertEqual(timeparse.timeparse('1 hours'),
                      3600)
     self.assertEqual(timeparse.timeparse('1 day'),
                      86400)
     self.assertEqual(timeparse.timeparse('1 sec'),
                      1)
开发者ID:catherinedevlin,项目名称:pytimeparse,代码行数:12,代码来源:testtimeparse.py


示例8: parse

def parse(executor, result, futures):
    for line in result.splitlines():
        words = line.split()

        if len(words) >= 5:
            status = words[4]
            namespace = words[0]
            name = words[1]
            idx = namespace + ":" + name
            if (status.startswith("Failed")) or (status == "Cancelled") or \
                    (status.startswith("Error")):
                if idx in global_build_status.keys():
                    logger.debug(idx + " FAILED")
                    if global_build_status[idx] < STATUS_NOT_COMPLETE:
                        global_build_status[idx] = STATUS_NOT_COMPLETE
                        stats_idx = idx[0:idx.rindex('-')]
                        global_build_stats[stats_idx]["failed"] += 1
            elif "Complete" == words[4]:
                if idx in global_build_status.keys():
                    if global_build_status[idx] < STATUS_COMPLETE:
                        logger.info(idx + " Complete")
                        global_build_status[idx] = STATUS_COMPLETE
                    duration_string = words[-1]
                    if global_build_status[idx] < STATUS_LOGGING:
                        futures.append(
                            executor.submit(do_post_actions, namespace,
                                            name, timeparse(duration_string)))
        else:
            logger.error("unexpected return "
                         "(oc get build --all-namespaces --no-headers): "
                         + result)
开发者ID:ekuric,项目名称:svt,代码行数:31,代码来源:build_test.py


示例9: parse_time_interval

def parse_time_interval(time_start, time_end):
    """created time values for time_start and time_end, while time_end
    will be replaced with time_start+ a duration if the duration is
    given in time_end. The format of the duration is intuitive through
    the timeparse module. YOu can specify values such as +1d, +1w10s.

    :param time_start: the start time, if the string 'current_time' is
                       passed it will be replaced by the current time

    :param time_end: either a time or a duration
    """
    t_end = time_end
    t_start = time_start

    if t_start is not None:
        if t_start in ["current_time", "now"]:
            t_start = str(datetime.now())

    if t_end is not None:
        if t_end.startswith("+"):
            duration = t_end[1:]
            delta = timeparse(duration)
            t_start = datetime.strptime(t_start, "%Y-%m-%d %H:%M:%S.%f")
            t_end = t_start + timedelta(seconds=delta)

    return (str(t_start), str(t_end))
开发者ID:lee212,项目名称:cloudmesh,代码行数:26,代码来源:tables.py


示例10: timedelta_type

def timedelta_type(value):
    """Return the :class:`datetime.datetime.DateTime` for a time in the past.
    :param value: a string containing a time format supported by :mod:`pytimeparse`
    """
    if value is None:
        return None
    return datetime_seconds_ago(timeparse.timeparse(value))
开发者ID:oktopuz,项目名称:paasta,代码行数:7,代码来源:delete_old_marathon_deployments.py


示例11: validate_interval

 def validate_interval(self, field):
     try:
         int(field.data)
     except ValueError:
         if timeparse(field.data) is None:
             raise ValidationError("interval must either be a number "
                                   "(in seconds) or a human-readable "
                                   "string like '1h2m'  or '1d12h'")
开发者ID:boyska,项目名称:larigira,代码行数:8,代码来源:timeform_base.py


示例12: check_window_valid

 def check_window_valid(window):
     """Takes in the window parameter string, reformats as a float."""
     if window is None:
         msg = 'Moving aggregate must have window specified.'
         raise aggregates.CustomAggFailure(msg)
     try:
         return float(timeparse.timeparse(six.text_type(window)))
     except Exception:
         raise aggregates.CustomAggFailure('Invalid value for window')
开发者ID:NeCTAR-RC,项目名称:gnocchi,代码行数:9,代码来源:moving_stats.py


示例13: parse_timedelta

def parse_timedelta(value):
    """Return the delta in nanoseconds.
    :param value: a string containing a time format supported by :mod:`pytimeparse`
    :returns: an integer (or float) representing the specified delta in nanoseconds
    """
    error_msg = "'%s' is not a valid time expression" % value
    try:
        seconds = timeparse.timeparse(value)
    except TypeError:
        raise argparse.ArgumentTypeError(error_msg)
    if not seconds:
        raise argparse.ArgumentTypeError(error_msg)
    return seconds_to_nanoseconds(seconds)
开发者ID:EvanKrall,项目名称:paasta,代码行数:13,代码来源:paasta_maintenance.py


示例14: generate_start_end_time

def generate_start_end_time(from_string="30m", to_string=None):
    """Parses the --from and --to command line arguments to create python
    datetime objects representing the start and end times for log retrieval

    :param from_string: The --from argument, defaults to 30 minutes
    :param to_string: The --to argument, defaults to the time right now
    :return: A tuple containing start_time, end_time, which specify the interval of log retrieval
    """
    if to_string is None:
        end_time = datetime.datetime.utcnow()
    else:
        # Try parsing as a a natural time duration first, if that fails move on to
        # parsing as an ISO-8601 timestamp
        to_duration = timeparse(to_string)

        if to_duration is not None:
            end_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=to_duration)
        else:
            end_time = isodate.parse_datetime(to_string)
            if not end_time:
                raise ValueError("--to argument not in ISO8601 format and not a valid pytimeparse duration")

    from_duration = timeparse(from_string)
    if from_duration is not None:
        start_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=from_duration)
    else:
        start_time = isodate.parse_datetime(from_string)

        if not start_time:
            raise ValueError("--from argument not in ISO8601 format and not a valid pytimeparse duration")

    # Covert the timestamps to something timezone aware
    start_time = pytz.utc.localize(start_time)
    end_time = pytz.utc.localize(end_time)

    if start_time > end_time:
        raise ValueError("Start time bigger than end time")

    return start_time, end_time
开发者ID:somic,项目名称:paasta,代码行数:39,代码来源:logs.py


示例15: test_timeparse_signs

 def test_timeparse_signs(self):
     '''Test parsing time signs.'''
     self.assertEqual(timeparse.timeparse('+32 m 1 s'), 1921)
     self.assertEqual(timeparse.timeparse('+ 32 m 1 s'), 1921)
     self.assertEqual(timeparse.timeparse('-32 m 1 s'), -1921)
     self.assertEqual(timeparse.timeparse('- 32 m 1 s'), -1921)
     self.assertIsNone(timeparse.timeparse('32 m - 1 s'))
     self.assertIsNone(timeparse.timeparse('32 m + 1 s'))
开发者ID:cackovic,项目名称:pytimeparse,代码行数:8,代码来源:testtimeparse.py


示例16: to_timespan

def to_timespan(value):
    if value is None:
        raise ValueError("Invalid timespan")
    try:
        seconds = int(value)
    except Exception:
        try:
            seconds = timeparse.timeparse(six.text_type(value))
        except Exception:
            raise ValueError("Unable to parse timespan")
    if seconds is None:
        raise ValueError("Unable to parse timespan")
    if seconds <= 0:
        raise ValueError("Timespan must be positive")
    return datetime.timedelta(seconds=seconds)
开发者ID:openstack-yak,项目名称:gnocchi,代码行数:15,代码来源:utils.py


示例17: to_timestamp

def to_timestamp(v):
    if isinstance(v, datetime.datetime):
        return v
    try:
        v = float(v)
    except (ValueError, TypeError):
        v = six.text_type(v)
        try:
            return timeutils.normalize_time(timeutils.parse_isotime(v))
        except ValueError:
            delta = timeparse.timeparse(v)
            if delta is None:
                raise ValueError("Unable to parse timestamp %s" % v)
            return timeutils.utcnow() + datetime.timedelta(seconds=delta)
    return datetime.datetime.utcfromtimestamp(v)
开发者ID:calvin67,项目名称:gnocchi,代码行数:15,代码来源:utils.py


示例18: __init__

 def __init__(self, obj):
     self.start = getdate(obj['start'])
     try:
         self.interval = int(obj['interval'])
     except ValueError:
         self.interval = timeparse(obj['interval'])
     assert type(self.interval) is int
     self.end = getdate(obj['end']) if 'end' in obj else None
     self.weekdays = [int(x) for x in obj['weekdays']] if \
         'weekdays' in obj else None
     if self.weekdays is not None:
         for weekday in self.weekdays:
             if not 1 <= weekday <= 7:
                 raise ValueError('Not a valid weekday: {}'
                                  .format(weekday))
开发者ID:boyska,项目名称:larigira,代码行数:15,代码来源:timegen_every.py


示例19: parse_time_interval

def parse_time_interval(time_start, time_end):
    t_end = time_end
    t_start = time_start

    if t_start is not None:
        if t_start in ["current_time", "now"]:
            t_start = str(datetime.now())

    if t_end is not None:
        if t_end.startswith("+"):
            duration = t_end[1:]
            delta = timeparse(duration)
            t_start = datetime.strptime(t_start, "%Y-%m-%d %H:%M:%S.%f")
            t_end = t_start + timedelta(seconds=delta)

    return (str(t_start), str(t_end))
开发者ID:rahulsinghania,项目名称:cloudmesh,代码行数:16,代码来源:cm_rain.py


示例20: run

  def run(self, events, *args, **kwargs):
    event = kwargs.pop('event')
    event_id = kwargs.pop('event_id')
    duration = kwargs.pop('duration')

    parsed_duration_in_seconds = timeparse(duration, granularity='minutes')
    event['duration'] = parsed_duration_in_seconds
    body = strings.MSG_DURATION_SET % datetime.timedelta(seconds=parsed_duration_in_seconds)
    calendar_event_id = event.get('calendar_event') and event['calendar_event']['id']
    if calendar_event_id:
      try:
        calendar_events.update_gcal_event(event, event_id)
      except calendar_events.KeyfilePathNotSpecifiedError:
        pass

    return RSVPCommandResponse(events, RSVPMessage('stream', body))
开发者ID:jjst,项目名称:RSVPBot,代码行数:16,代码来源:rsvp_commands.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python devices.Light类代码示例发布时间:2022-05-27
下一篇:
Python utils.check_positive函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap