本文整理汇总了Python中pytimeparse.timeparse.timeparse函数的典型用法代码示例。如果您正苦于以下问题:Python timeparse函数的具体用法?Python timeparse怎么用?Python timeparse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了timeparse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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))
示例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))
示例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'")
示例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')
示例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)
示例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
示例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'))