MCPcopy Create free account
hub / github.com/ActiveState/code / strptime

Function strptime

recipes/Python/56036_Pure_Python_strptime/recipe-56036.py:322–438  ·  view source on GitHub ↗

Return a time struct based on the input string and the format string.

(data_string, format="%a %b %d %H:%M:%S %Y")

Source from the content-addressed store, hash-verified

320_regex_cache = {}
321
322def strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
323 """Return a time struct based on the input string and the format string."""
324 global _TimeRE_cache
325 _cache_lock.acquire()
326 try:
327 time_re = _TimeRE_cache
328 locale_time = time_re.locale_time
329 if _getlang() != locale_time.lang:
330 _TimeRE_cache = TimeRE()
331 if len(_regex_cache) > _CACHE_MAX_SIZE:
332 _regex_cache.clear()
333 format_regex = _regex_cache.get(format)
334 if not format_regex:
335 format_regex = time_re.compile(format)
336 _regex_cache[format] = format_regex
337 finally:
338 _cache_lock.release()
339 found = format_regex.match(data_string)
340 if not found:
341 raise ValueError("time data did not match format: data=%s fmt=%s" %
342 (data_string, format))
343 if len(data_string) != found.end():
344 raise ValueError("unconverted data remains: %s" %
345 data_string[found.end():])
346 year = 1900
347 month = day = 1
348 hour = minute = second = 0
349 tz = -1
350 # weekday and julian defaulted to -1 so as to signal need to calculate values
351 weekday = julian = -1
352 found_dict = found.groupdict()
353 for group_key in found_dict.keys():
354 if group_key == 'y':
355 year = int(found_dict['y'])
356 # Open Group specification for strptime() states that a %y
357 #value in the range of [00, 68] is in the century 2000, while
358 #[69,99] is in the century 1900
359 if year <= 68:
360 year += 2000
361 else:
362 year += 1900
363 elif group_key == 'Y':
364 year = int(found_dict['Y'])
365 elif group_key == 'm':
366 month = int(found_dict['m'])
367 elif group_key == 'B':
368 month = locale_time.f_month.index(found_dict['B'].lower())
369 elif group_key == 'b':
370 month = locale_time.a_month.index(found_dict['b'].lower())
371 elif group_key == 'd':
372 day = int(found_dict['d'])
373 elif group_key == 'H':
374 hour = int(found_dict['H'])
375 elif group_key == 'I':
376 hour = int(found_dict['I'])
377 ampm = found_dict.get('p', '').lower()
378 # If there was no AM/PM indicator, we'll treat this like AM
379 if ampm in ('', locale_time.am_pm[0]):

Callers 3

_getWeekDetailsFunction · 0.90
getEpsFunction · 0.90
__init__Method · 0.90

Calls 14

_getlangFunction · 0.85
TimeREClass · 0.85
enumerateFunction · 0.70
acquireMethod · 0.45
clearMethod · 0.45
getMethod · 0.45
compileMethod · 0.45
releaseMethod · 0.45
matchMethod · 0.45
endMethod · 0.45
keysMethod · 0.45
indexMethod · 0.45

Tested by

no test coverage detected