How to use parse_iso8601_time method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

iso8601.py

Source:iso8601.py Github

copy

Full Screen

1# -*- python -*-2# Handling full ISO 8601:2019 datetime string.3#4# https://github.com/yoiwa-personal/python-iso8601-full/5#6# Copyright 2019 Yutaka OIWA <yutaka@oiwa.jp>.7#8# Licensed under the Apache License, Version 2.0 (the "License");9# you may not use this file except in compliance with the License.10# You may obtain a copy of the License at11#12# http://www.apache.org/licenses/LICENSE-2.013#14# Unless required by applicable law or agreed to in writing, software15# distributed under the License is distributed on an "AS IS" BASIS,16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.17# See the License for the specific language governing permissions and18# limitations under the License.19# This modules handles rarely-used uncommon variations of date20# representation strings defined in ISO 8601:2019.21#22# See also rfc3339.py for simple, commonly-used subset of this format.23# It is licensed with CC0 (dedicated to public domain).24"""Handling full ISO 8601:2019 datetime string.25The module parses complex date/time representation strings formatted26according to ISO 8601:2019.27It accepts all format of date/time specifications defined in the ISO28standard, for example:29 * An usual day-of month: 2019-12-12 or 2019121230 * A day-of-year notation: 2019-346 or 201934631 * A day-of-week notation: 2019-W50-4 or 2019W50432 * Abbreviated period of days: 2019-12, 2019, 20 etc.33 * Extended notion of years: +002019-12-12, -0004-12-2534 * A sub-second time notation: 12:34:56.78 or 123456.7835 * Abbreviated period of times: 12, 12:3436 * Those with sub-unit fractions: 12.5, 12:34.567837 * Variable decimal separator: 12:34:56,7838 * Combined date-time: 2019-12-12T12:34.539 * Timezone offsets: 2019-12-12T12:34.5+09, 20191212T123430+090040Provided functions are 'parse_ISO8601_date', 'parse_ISO8601_time',41'parse_ISO8601_datetime'.42Note: It does not accept obsolete formats (e.g. 2-digit year like4319-12-12 or 191212) defined in ISO 8601:1999.44"""45__author__ = 'Yutaka OIWA <yutaka@oiwa.jp>'46__all__ = ['parse_ISO8601_date', 'parse_ISO8601_time', 'parse_ISO8601_datetime']47import re48import datetime as datetime_49from datetime import timedelta50_zerodelta = timedelta(0)51_single_sec = timedelta(seconds=1)52_single_day = timedelta(days=1)53try:54 from datetime import timezone55 _timezone_utc = timezone.utc56except ImportError:57 class timezone(datetime_.tzinfo):58 def __init__(self, ofs):59 self.__offset = ofs60 self.__name = self._compute_name(ofs)61 def utcoffset(self, dt): return self.__offset62 def tzname(self, dt): return self.__name63 def dst(self, dt): return _zerodelta64 @classmethod65 def _compute_name(self, ofs):66 # minimal implementation!67 sg, s = 1, ofs.seconds + ofs.days * 8640068 if s < 0: (sg, s) = (-1, -s) # needed for -03:30 timezone69 s //= 6070 h, m = (s // 60, s % 60)71 return "UTC%+03d:%02d" % (h * sg, m)72 _timezone_utc = timezone(_zerodelta)73from datetime import datetime, date, time74datepart = (r"""(?x:(?P<EXT>-?)75 (?:(?P<M>[01]\d)(?P=EXT)(?P<D>[0-3]\d)76 |(?P<YD>[0-3]\d\d)77 |[Ww](?P<W>[0-5]\d)(?:(?P=EXT)(?P<WD>[1-7]))?)78 |-(?P<MO>[01]\d))""")79yearpart = r"""(?P<CY>\d\d)"""80centurypart_tmpl = r"""(?P<C>(?:[+-]\d{%d,}?)?\d\d)"""81date_regex_num = lambda n: re.compile("\A" + (centurypart_tmpl % n) +82 "(?:" + yearpart + "(?:" + datepart + ")?)?\Z")83date_regex = date_regex_num(0)84date_regexs = {}85def parse_date_to_tuple(s, digits_year_ext=4):86 if digits_year_ext <= 4:87 r = date_regex88 elif digits_year_ext in date_regexs:89 r = date_regexs[digits_year_ext]90 else:91 r = date_regexs[digits_year_ext] = date_regex_num(digits_year_ext - 4)92 m = r.match(s)93 if not m:94 raise ValueError("invalid date string")95 m = m.groupdict()96 if m["D"] is not None:97 return ("day", int(m["C"] + m["CY"]), int(m["M"]), int(m["D"]))98 elif m["YD"] is not None:99 return ("day-year", int(m["C"] + m["CY"]), int(m["YD"]))100 elif m["WD"] is not None:101 return ("day-week", int(m["C"] + m["CY"]), int(m["W"]), int(m["WD"]))102 elif m["W"] is not None:103 return ("week", int(m["C"] + m["CY"]), int(m["W"]))104 elif m["MO"] is not None:105 return ("month", int(m["C"] + m["CY"]), int(m["MO"]))106 elif m["CY"] is not None:107 return ("year", int(m["C"] + m["CY"]))108 elif m["C"] is not None:109 return ("century", int(m["C"]))110 else:111 return False112_get = lambda l, i, d: l[i] if len(l) > i else d113def date_tuple_to_start(m, digits_year_ext=4):114 if m[0] in ("day", "month", "year"):115 return date(m[1], _get(m, 2, 1), _get(m, 3, 1))116 elif m[0] == "day-year":117 return date(m[1], 1, 1) + timedelta(days=(m[2] - 1))118 elif m[0] in ("day-week", "week"):119 year = m[1]120 week = m[2]121 wday = _get(m, 3, 1)122 try:123 return datetime.fromisocalendar(year,week,wday)124 except AttributeError:125 day1 = date(m[1], 1, 1)126 wday1 = day1.isoweekday()127 delta = (1 - wday1) if wday1 <= 4 else (8 - wday1)128 delta += (week - 1) * 7 + (wday - 1)129 return day1 + timedelta(days=delta)130 elif m[0] == "century":131 # actually, it's hundred-year, not century (0-start)132 return date(m[1] * 100, 1, 1)133 else:134 raise AssertionError("should not happen: unknown type")135def parse_date_to_start(s, digits_year_ext=4):136 m = parse_date_to_tuple(s, digits_year_ext);137 return date_tuple_to_start(m, digits_year_ext=digits_year_ext)138def parse_date_to_start_duration(s, digits_year_ext=4):139 m = parse_date_to_tuple(s, digits_year_ext);140 day = date_tuple_to_start(m, digits_year_ext=digits_year_ext)141 if m[0] in ("day", "day-year", "day-week"):142 return day, _single_day143 elif m[0] == "week":144 return day, timedelta(days=7)145 elif m[0] == "month":146 m2 = day.month + 1147 day2 = (date(day.year, m2, 1) if m2 != 13148 else date(day.year + 1, 1, 1))149 return day, day2 - day150 elif m[0] == "year":151 day2 = date(day.year + 1, 1, 1)152 return day, day2 - day153 elif m[0] == "century":154 day2 = date(day.year + 100, 1, 1)155 return day, day2 - day156 else:157 raise AssertionError("should not happen: unknown type")158class dateWithPrecision(date):159 __slots__ = ("precision",)160 def __new__(self, d, p):161 o = super(dateWithPrecision, self).__new__(self, d.year, d.month, d.day)162 o.precision = p163 return o164 def __init__(self, d, p):165 pass166def parse_ISO8601_date(s, digits_year_ext=4):167 """Parse a date string formatted in ISO 8601 syntax.168 An optional argument digits_year_ext specifies how many digits169 are expected for the extended year specification (prefixed by170 `+` or `-`).171 Returned value is an extended `date` object pointing to the start172 day of the input. An additional property `precision` is set to a173 `timedelta` object specifying a length of the specified calendar174 date period.175 """176 d, p = parse_date_to_start_duration(s, digits_year_ext=digits_year_ext)177 return dateWithPrecision(d, p)178time_regexp = re.compile(179 r'''(?x)\A(?P<H>\d\d)180 (?:(?P<HF>[,.]\d+)181 |(?P<EXT>:?)(?P<M>\d\d)182 (?:(?P<MF>[,.]\d+)183 |(?P=EXT)(?P<S>\d\d)(?P<SF>[,.]\d+)?)?)?184 (?P<TZ>|[Zz]|(?P<TZSIGN>[-+])(?P<TZH>\d\d)((?::?)(?P<TZM>\d\d))?)?\Z''')185def _frac_to_spec(s):186 if not s:187 return 0, 1188 if s[0:1] not in ('.', ','):189 raise ValueError(s)190 s = s[1:]191 expo = len(s or "")192 return (int(s or "0"), 10 ** expo)193def parse_time_to_tuple(s):194 m = time_regexp.match(s)195 if not m:196 raise ValueError("invalid time spec")197 m = m.groupdict()198 # timezone199 if m['TZ'] == '':200 tz = None201 elif m['TZ'] in ('Z', 'z'):202 tz = _timezone_utc203 else:204 tzhour = m['TZH']205 tzminute = (m['TZM'] or "00")206 tzofs = timedelta(hours=int(tzhour), minutes=int(tzminute))207 if m['TZSIGN'] == '-': tzofs = -tzofs208 tz = timezone(tzofs)209 if m['S'] is not None:210 numer, denom = _frac_to_spec(m['SF'])211 return ("s", int(m['H']), int(m['M']), int(m['S']), numer, denom, 1, tz)212 elif m['M'] is not None:213 numer, denom = _frac_to_spec(m['MF'])214 return ("m", int(m['H']), int(m['M']), 0, numer, denom, 60, tz)215 elif m['H'] is not None:216 numer, denom = _frac_to_spec(m['HF'])217 return ("h", int(m['H']), 0, 0, numer, denom, 3600, tz)218def time_tuple_to_start_prec(t, leapsecond=0):219 (type, hour, minute, second, numer, denom, scale, tz) = t220 duration = timedelta(microseconds = 1000000.0 / denom * scale)221 if duration == _zerodelta: duration = timedelta.resolution222 if (hour == 24):223 if minute == second == numer == 0:224 return(time(23, 59, 59), _single_sec, None, duration)225 if (hour < 0 or minute < 0 or second < 0226 or hour >= 24 or minute >= 60 or second > 60 or227 numer < 0 or numer >= denom or denom < 0 or scale <= 0):228 raise ValueError229 delta = _zerodelta230 leap = None231 microsecond = 1000000 * numer * scale // denom232 if second == 60: # leap second233 if scale != 1 or microsecond >= 1000000:234 raise AssertionError("not happen")235 if leapsecond == -1:236 second = 59237 leap = _single_sec238 elif leapsecond == 0:239 leap = timedelta(microseconds=microsecond)240 microsecond = 0241 elif leapsecond == 1:242 leap = _zerodelta243 else:244 raise LeapSecondValueError245 # adjust for fraction246 if microsecond >= 1000000:247 second += microsecond // 1000000248 microsecond = microsecond % 1000000249 if second >= 60:250 minute += second // 60251 second = second % 60252 if minute >= 60:253 hour += minute // 60254 minute = minute % 60255 # adjust for overflow by 24:00 or --:--:60256 if (hour >= 24):257 minute += 60 * (hour - 23)258 hour = 23259 if (minute >= 60):260 second += 60 * (minute - 59)261 minute = 59262 if (second >= 60):263 delta = _single_sec * (second - 59)264 second = 59265 t = time(hour, minute, second, microsecond, tzinfo=tz)266 return (t, delta, leap, duration)267def parse_time_to_start_prec(s, leapsecond=0):268 t = parse_time_to_tuple(s)269 return time_tuple_to_start_prec(t, leapsecond=leapsecond)270class timeWithPrecision(time):271 __slots__ = ("precision", "leap", "delta")272 def __new__(self, t, delta, leap, precision):273 o = super(timeWithPrecision, self).__new__(self, t.hour, t.minute, t.second, t.microsecond, tzinfo=t.tzinfo)274 o.delta = delta275 o.leap = leap276 o.precision = precision277 return o278 def __init__(self, t, delta, leap, precision):279 pass280def parse_ISO8601_time(s, leapsecond=0, with_delta=False):281 """Parse a time-in-day string formatted in ISO 8601 syntax.282 Optional named arguments are as follows:283 with_delta: a boolean whether a returned value can be offseted,284 using a special property `delta` described below, to285 represent time values above 24:00:00, which are not286 normally allowed by the Python's `time` object.287 See also property `delta` described below.288 leapsecond: specifies how the 60th second is to be treated:289 -1: the preceeding 59th second is repeated.290 0: the clock holds at the top of the next 0th second.291 +1: the next 0th second is repeated.292 "raise": raise a Value Error.293 The argument `with_delta` should also be set to true294 to handle "23:59:60", unless `leapsecond` is set to -1.295 Returned value is an `time` object with the following additional296 properties:297 delta: If with_delta is set to True, it is a `timedelta` object298 representing an extra offset overflowed from the allowed299 time range.300 It might happen when either "24:00:00" or "23:59:60.xxx"301 is specified.302 If with_delta is False (default), this property is fixed303 to `timedelta(0)`, and ValueError is raised for any304 overflow cases.305 leap: It is set to None if 60th second is not specified.306 If a 60th second is input, the property is set to a307 `timedelta` object representing the time reduced by the308 handling of the leap second. (delta offset shall be309 considered before using this.)310 Be careful that the value might be 0 sec, which is treated311 as a false value in boolean contexts.312 precision: a `timedelta` object representing a width of the313 time-range specified in the input.314 It might be either an hour, a minute or a second315 divided by any power of ten.316 """317 t, delta, leap, precision = parse_time_to_start_prec(s, leapsecond=leapsecond)318 if not with_delta:319 if delta != _zerodelta:320 raise ValueError("time overflow (24:00:00)")321 return timeWithPrecision(t, delta, leap, precision)322datetime_sep_regexp = re.compile(r'\A(.+?)([Tt](.+))\Z')323class datetimeWithPrecision(datetime):324 __slots__ = ("leap", "precision",)325 def __new__(self, dt, leap, prec):326 o = super(datetimeWithPrecision, self).__new__(327 self,328 dt.year, dt.month, dt.day,329 dt.hour, dt.minute, dt.second, dt.microsecond,330 tzinfo=dt.tzinfo)331 o.leap = leap332 o.precision = prec333 return o334 def __init__(self, dt, leap, prec):335 pass336# TODO: consistency of extended/normal notations between components are not checked337def parse_ISO8601_datetime(s, digits_year_ext=4, leapsecond=0):338 """Parse a date string formatted in ISO 8601 syntax.339 An optional argument digits_year_ext specifies how many digits340 are expected for the extended year specification (prefixed by341 `+` or `-`).342 An optional argument leapsecond specifies how the 60th second is343 treated:344 -1: the preceeding 59th second is repeated.345 0: the clock holds at the top of the next 0th second.346 +1: the next 0th second is repeated.347 "raise": raise a Value Error.348 Returned value is either a `date` or `datetime` object, with the349 following properties:350 precision: a `timedelta` object representing a width of thte351 timerange specified in the input.352 leap: the field is only avaiable if time-part is specified.353 Either `None` if leap second is not specified, or a354 `timedelta` object (might be 0-time) representing a time355 duration rounded by the treatment of the 60th second.356 """357 match = datetime_sep_regexp.match(s)358 if match:359 date, duration = parse_date_to_start_duration(match.group(1), digits_year_ext=digits_year_ext)360 if duration > _single_day:361 raise ValueError("not-a-single-day date with a specific time")362 t = parse_time_to_start_prec(match.group(3), leapsecond=leapsecond)363 if not t: return t364 time, delta, leap, duration = t365 date_time = datetime.combine(date, time)366 date_time += delta367 return datetimeWithPrecision(date_time, leap, duration)368 else:...

Full Screen

Full Screen

xmlrpc.py

Source:xmlrpc.py Github

copy

Full Screen

...94 if not content:95 raise Fault(400, 'Save failed, the article content cannot be empty.')96 try:97 if 'dateCreated' in struct:98 time = parse_iso8601_time(struct['dateCreated'].value)99 else:100 time = datetime.utcnow()101 except:102 time = datetime.utcnow()103 if REPLACE_SPECIAL_CHARACTERS_FOR_URL:104 url = formatted_date_for_url(time) + replace_special_characters_for_url(title)105 else:106 url = formatted_date_for_url(time) + title107 if Article.all().filter('url =', url).count(1):108 raise Fault(400, 'Save failed, there is already an article with the same URL.')109 tags = []110 try:111 if 'mt_keywords' in struct:112 tags = struct['mt_keywords'].strip().split()113 tags = list(set(tags))114 except:115 pass116 category = None117 try:118 if 'categories' in struct:119 categories = struct['categories']120 if categories:121 category = categories[0].strip() or None122 except:123 pass124 try:125 article = Article(126 title=title,127 url=url,128 content=content,129 format=CONTENT_FORMAT_FLAG['html'],130 published=publish,131 tags=tags,132 category=category,133 time=time,134 mod_time=time135 )136 article.put()137 try:138 if tags:139 tags = Tag.get_by_key_name(tags)140 tag_set = set(tags)141 tag_set.discard(None)142 tags = list(tag_set)143 if tags:144 for tag in tags:145 tag.count += 1146 db.put(tags)147 except:148 pass149 if publish:150 clear_article_memcache()151 deferred.defer(ping_hubs, BLOG_FEED_URL)152 deferred.defer(ping_xml_rpc, BLOG_HOME_FULL_URL + article.quoted_url())153 return str(article.key().id())154 except:155 raise Fault(500, 'Save failed, the datastore has some error or is busy now.')156 @staticmethod157 @authorized()158 def editPost(postid, struct, publish):159 article = get_article_by_id(postid)160 if 'title' not in struct:161 raise Fault(400, 'Edit failed, the article title cannot be empty.')162 title = strip(struct['title'])163 if not title:164 raise Fault(400, 'Edit failed, the article title cannot be empty.')165 article.title = title166 if 'description' not in struct:167 raise Fault(400, 'Edit failed, the article content cannot be empty.')168 content = struct['description']169 if not content:170 raise Fault(400, 'Edit failed, the article content cannot be empty.')171 article.content = content172 article.format = CONTENT_FORMAT_FLAG['html']173 article.published = publish174 try:175 if 'dateCreated' in struct:176 time = parse_iso8601_time(struct['dateCreated'].value)177 article_time = article.time178 if time != article_time:179 if time > article_time:180 if time - article_time > ONE_SECOND:181 article.time = time182 else:183 if article_time - time > ONE_SECOND:184 article.time = time185 except:186 pass187 article.mod_time = datetime.utcnow()188 tags = []189 old_tags = set(article.tags)190 try:...

Full Screen

Full Screen

test_report.py

Source:test_report.py Github

copy

Full Screen

...9from helpers.runner import run_suite_class10NOW = time.time()11CURRENT_YEAR = time.localtime().tm_year12def _test_timestamp_round(raw, rounded):13 assert parse_iso8601_time(format_time_as_iso8601(raw)) == rounded14def test_format_and_parse_iso8601_time_1():15 _test_timestamp_round(1485093460.874194, 1485093460.874)16def test_format_and_parse_iso8601_time_2():17 _test_timestamp_round(1485093460.874794, 1485093460.875)18def test_format_and_parse_iso8601_time_3():19 _test_timestamp_round(1485093460.999001, 1485093460.999)20def test_format_and_parse_iso8601_time_4():21 _test_timestamp_round(1485093460.999999, 1485093461.0)22def test_format_and_parse_iso8601_time_5():23 _test_timestamp_round(1485105524.353112, 1485105524.353)24def test_report_stats_simple():25 report = make_report(suites=[26 make_suite_result(tests=[27 make_test_result(steps=[make_step(logs=[make_check(True)])])...

Full Screen

Full Screen

stack.py

Source:stack.py Github

copy

Full Screen

...69 url = "https://pricing.vexxhost.net/v1/pricing/%s/cost?seconds=%d"70 with urllib.request.urlopen(url % (flavor, seconds)) as response: # nosec71 data = json.loads(response.read())72 return data["cost"]73 def parse_iso8601_time(time):74 return datetime.strptime(time, "%Y-%m-%dT%H:%M:%S.%f")75 def get_server_info(server_id):76 server = cloud.compute.find_server(server_id)77 diff = datetime.utcnow() - parse_iso8601_time(server.launched_at)78 return server.flavor["original_name"], diff.total_seconds()79 def get_server_ids(stack_name):80 servers = get_resources_by_type(stack_name, "OS::Nova::Server")81 return [s["physical_resource_id"] for s in servers]82 def get_resources_by_type(stack_name, resource_type):83 resources = get_stack_resources(stack_name)84 return [r for r in resources if r.resource_type == resource_type]85 def get_stack_resources(stack_name):86 resources = []87 def _is_nested(resource):88 link_types = [link["rel"] for link in resource.links]89 if "nested" in link_types:90 return True91 return False...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Lemoncheesecake automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful