| | 274 | |
| | 275 | def timeparse(t, format): |
| | 276 | """Parse a time string that might contain fractions of a second. |
| | 277 | |
| | 278 | Fractional seconds are supported using a fragile, miserable hack. |
| | 279 | Given a time string like '02:03:04.234234' and a format string of |
| | 280 | '%H:%M:%S', time.strptime() will raise a ValueError with this |
| | 281 | message: 'unconverted data remains: .234234'. If %S is in the |
| | 282 | format string and the ValueError matches as above, a datetime |
| | 283 | object will be created from the part that matches and the |
| | 284 | microseconds in the time string. |
| | 285 | |
| | 286 | Found at: http://www.thescripts.com/forum/thread506538.html |
| | 287 | """ |
| | 288 | |
| | 289 | try: |
| | 290 | return datetime.datetime(*time.strptime(t, format)[0:6]) |
| | 291 | except ValueError, msg: |
| | 292 | if "%S" in format: |
| | 293 | msg = str(msg) |
| | 294 | regex_types = ( |
| | 295 | r"unconverted data remains: \.([0-9]{1,6})$", |
| | 296 | r"unconverted data remains: \,([0-9]{3,3})$" |
| | 297 | ) |
| | 298 | |
| | 299 | for regex in regex_types: |
| | 300 | mat = re.match(regex, msg) |
| | 301 | |
| | 302 | if mat is not None: |
| | 303 | # fractional seconds are present - this is the style |
| | 304 | # used by datetime's isoformat() method |
| | 305 | frac = "." + mat.group(1) |
| | 306 | t = t[:-len(frac)] |
| | 307 | t = datetime.datetime(*time.strptime(t, format)[0:6]) |
| | 308 | microsecond = int(float(frac)*1e6) |
| | 309 | return t.replace(microsecond=microsecond) |
| | 310 | raise |
| | 311 | |