Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: How to parse timestamps containing milliseconds

Reply
Thread Tools

Re: How to parse timestamps containing milliseconds

 
 
skip@pobox.com
Guest
Posts: n/a
 
      06-28-2006

Chris> I'm trying to read a file containing timestamps with milliseconds
Chris> ("2006/3/18 8:20:34.050").... When I try to parse I get an error
Chris> about the trailing ".050".

Chris> How should I approach this?

Here's the bad hack I use...

def timeparse(t, format):
"""Parse a time string that might contain fractions of a second.

Fractional seconds are supported using a fragile, miserable hack.
Given a time string like '02:03:04.234234' and a format string of
'%H:%M:%S', time.strptime() will raise a ValueError with this
message: 'unconverted data remains: .234234'. If %S is in the
format string and the ValueError matches as above, a datetime
object will be created from the part that matches and the
microseconds in the time string.
"""
try:
return datetime.datetime(*time.strptime(t, format)[0:6]).time()
except ValueError, msg:
if "%S" in format:
msg = str(msg)
mat = re.match(r"unconverted data remains:"
" \.([0-9]{1,6})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by datetime's isoformat() method
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)
else:
mat = re.match(r"unconverted data remains:"
" \,([0-9]{3,3})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by the logging module
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)

raise

Skip
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Parse and find charater in a stream containing \x ... uap12 Java 2 03-17-2010 06:14 AM
parse a textfile containing japanese characters tej Java 6 11-01-2006 12:58 PM
How to parse huge file with timestamps jobs239@hotmail.com Java 1 11-30-2005 11:02 PM
email timestamps? joseph white Firefox 1 12-28-2004 09:12 PM



Advertisments