Using struct timeval in python

David wizzardx at gmail.com
Sat Sep 8 15:26:14 EDT 2007


On 9/8/07, sapsi <saptarshi.guha at gmail.com> wrote:
> Hi,
> I am using a library (pcapy) that returns a timeval object T=
> (seconds,microseconds) where microseconds is always < 1e6.
> Is there a Python class that can handle timeval structs? Specifically,
> I wish to subtract two T (defined above) objects, taking into account
> the large values of T[0] and T[1] (esp T[0])?
>
> At one point, I would have to step in, since T[0] rolls back to zero
> (after some time).

The Pythonic way would be to convert directly to a datetime (or
perhaps timedelta) object as soon as you receive your (seconds,
microseconds) tuple. Then you can subtract etc easily and interoperate
nicely with the rest of the standard python library.

But if you want to keep it in tuple format then you will probably need
to roll your own. eg: subclass tuple and override the __sub__ method.
Just make sure you handle negative values correctly (ie, what
(seconds,microseconds) you should end up with when you subtract a
later timval from an earlier timeval).

Alternatively you could convert to and from datetime as you need to
(perhaps subclassing and adding methods for easier conversion), but
that would be more expensive.



More information about the Python-list mailing list