Re: How to parse timestamps containing milliseconds

Discussion in 'Python' started by skip@pobox.com, Jun 28, 2006.

  1. Guest

    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
     
    , Jun 28, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chumma Dede
    Replies:
    2
    Views:
    400
    Chumma Dede
    Feb 11, 2005
  2. Craig G

    Using SQL TimeStamps in datagrid

    Craig G, Feb 28, 2005, in forum: ASP .Net
    Replies:
    4
    Views:
    441
    bruce barker
    Mar 1, 2005
  3. sconeek

    Comparint timestamps

    sconeek, Nov 29, 2005, in forum: Java
    Replies:
    4
    Views:
    430
    Roedy Green
    Nov 29, 2005
  4. Replies:
    1
    Views:
    387
    Roedy Green
    Nov 30, 2005
  5. Martin Bless
    Replies:
    1
    Views:
    2,873
    Matt Gerrans
    Dec 9, 2004
Loading...

Share This Page