Handling fractions of seconds in strftime/strptime

skip at pobox.com skip at pobox.com
Fri Jan 14 20:17:16 EST 2005


I'm looking for a solution (or ideas about a solution) to the problem
that strftime(3) and strptime(3) don't understand time increments of
less than one second.  Most operating systems can provide times with
subsecond resolution and like Python I'm pretty sure Ruby, Perl and
Tcl have objects or packages that can manipulate such times in a sane
manner.  I'm casting my net to a broader community than just Python
(where I generally hang out) to see if/how others have addressed this
problem.

Here's my typical use case.  I generate log files with subsecond
resolution using Python's datetime module.  By default it generates
printable timestamps in an ISO format that includes fractions of
seconds, e.g., "2005-01-14 18:56:54.546607".  I often need to parse
such times, and therein lies the rub.  Python's date parsing is based
on strptime(3) which can't handle fractions of seconds.  I wind up
worming around the problem with a little hackery, but it bothers me
that given an otherwise complete solution to formatting and parsing
times I can't handle this common (for me) case.

I realize that other languages may not base their current time
formatting and parsing on strftime(3) and strptime(3), but I suspect
those two functions were at least the root of what is commonly used by
most languages.  In my investigation I came across a DateTime module
in Perl that uses "%N" (or optionally "%nN" where n is a digit) to
identify integers as nanoseconds or some other subsecond time.  I
belive "%3N" would cause "123" to be interpreted as 123 milliseconds,
for instance.  I've considered extending "%S" to accept fractional
seconds or adding a new format specifier like "%F" to handle this
case.

I'm interested to know what solutions have been devised or considered
for other languages.  (Has this been addressed in some more recent
version of the C or C++ standards I'm unaware of?) Rather than
reinventing the wheel I'd like to adopt an existing solution if
possible. At the very least I'd like to know how others have
approached the problem.  I think there's an opportunity to add some
value that everyone can take advantage of.
Thanks for your time,

Skip Montanaro
skip at pobox.com




More information about the Python-list mailing list