Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python fraction of seconds

Tags:

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.

like image 783
TimothyAWiseman Avatar asked Dec 05 '09 00:12

TimothyAWiseman


2 Answers

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.

like image 142
Don O'Donnell Avatar answered Sep 27 '22 23:09

Don O'Donnell


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 
like image 25
ChristopheD Avatar answered Sep 28 '22 00:09

ChristopheD