views:

199

answers:

4

What is the best way to handle portions of a second in Python? The datetime library is excellent, but as far as I can tell it cannot handle any unit less than a second.

A: 

For what purpose? import time -> time.clock() returns the current time in milliseconds, so it can be used for timing purposes to millisecond accuracy.

Sean
+4  A: 

To get a better answer you'll need to specify your question further, but this should show at least how datetime can handle microseconds:

>>> from datetime import datetime
>>> t=datetime.now()
>>> t.microsecond
519943
ChristopheD
+3  A: 

In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds:

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2009, 12, 4, 23, 3, 27, 343000)
>>> now.microsecond
343000

if you want to display a datetime with fractional seconds, just insert a decimal point and strip trailing zeros:

>>> now.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')
'2009-12-04 23:03:27.343'

the datetime and time classes only accept integer input and hours, minutes and seconds must be between 0 to 59 and microseconds must be between 0 and 999999. The timedelta class, however, will accept floating point values with fractions and do all the proper modulo arithmetic for you:

>>> span = timedelta(seconds=3662.567)
>>> span
datetime.timedelta(0, 3662, 567000)

The basic components of timedelta are day, second and microsecond (0, 3662, 567000 above), but the constructor will also accept milliseconds, hours and weeks. All inputs may be integers or floats (positive or negative). All arguments are converted to the base units and then normalized so that 0 <= seconds < 60 and 0 <= microseconds < 1000000.

You can add or subtract the span to a datetime or time instance or to another span. Fool around with it, you can probably easily come up with some functions or classes to do exaxtly what you want. You could probably do all your date/time processing using timedelta instances relative to some fixed datetime, say basetime = datetime(2000,1,1,0,0,0), then convert to a datetime or time instance for display or storage.

Don O'Donnell
Thanks, that is exactly what I needed.
TimothyAWiseman
@timothy: You're welcome, glad I could help. If this is your accepted answer I would appreciate a check. Thanks.
Don O'Donnell
+1  A: 

NumPy 1.4 (in release candidate stage) has support for its own Date and DateArray objects. The one advantage is that it supports frequencies smaller than femtoseconds: http://projects.scipy.org/numpy/browser/trunk/doc/neps/datetime-proposal.rst

Otherwise I would go with the regular datetime subsecond frequencies.

akoumjian