How to get milliseconds when substructing datetime objects?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 12 18:13:22 EST 2007


En Wed, 12 Dec 2007 11:40:24 -0300, Dmitri O.Kondratiev  
<dokondr at gmail.com> escribió:

> Please help to find simple solutiion for measuring times of operations  
> with
> millisecond precision.
> For this I am trying to use datetime() objects:
>
> import time
> import datetime
>
> def dreamTime(secs):
>     t1 = datetime.datetime.now()
>     time.sleep(secs)
>     t2 = datetime.datetime.now()
>     dt = t2 - t1
>     print "Start time: "+str(t1)
>     print "Stop  time: "+str(t2)
>     print "Dream time sec: "+str(dt)
>     """
>     # The following code results in errors like:
>     # AttributeError: 'datetime.timedelta' object has no attribute  
> 'second'
>     """
>     dts = dt.second
>     dtmicro = dt.microsecond
>     dtmilli = dts * 1000 + dtmicro / float(1000)
>     dts2 = dtmilli / float(1000)
>     print "Dream Millies: "+str(dtmilli)
>     print "Dream Seconds, again: "+str(dts2)

Reading the docs at http://docs.python.org/lib/datetime-timedelta.html you  
can see that timedelta objects have a "seconds" attribute (not "second").

Ok, and how do you know that in the first place? There are several ways  
you can get this information from Python itself, just open the interpreter  
and see:

py> import datetime
py> t1=datetime.datetime.now()
py> t2=datetime.datetime.now()
py> dt=t2-t1
py> dt
datetime.timedelta(0, 5, 969000)

In case you didn't know what type dt is:

py> type(dt)
<type 'datetime.timedelta'>
py> repr(dt)
'datetime.timedelta(0, 5, 969000)'

Now you can now look for "timedelta" inside the Help files.
A quick way to enumerate attributes is to use dir():

py> dir(dt)
['__abs__', '__add__', '__class__', ......, '__sub__',
'days', 'max', 'microseconds', 'min', 'resolution', 'seconds']

Look at 'seconds' there. Another useful function is vars(), but doesn't  
work for this kind of object; just as an example, I'll show vars(datetime):

py> vars(dt)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
py> vars(datetime)
{'timedelta': <type 'datetime.timedelta'>, 'MAXYEAR': 9999, 'datetime':  
<type 'd
atetime.datetime'>, 'date': <type 'datetime.date'>, 'datetime_CAPI':  
<PyCObject
object at 0x009BA290>, 'tzinfo': <type 'datetime.tzinfo'>, 'time': <type  
'dateti
me.time'>, 'MINYEAR': 1, '__name__': 'datetime', '__doc__': 'Fast  
implementation
  of the datetime type.'}

Using the built-in help system:

py> help(dt)
Help on timedelta object:

class timedelta(__builtin__.object)
  |  Difference between two datetime values.
  |
  |  Methods defined here:
  |
  |  __abs__(...)
  |      x.__abs__() <==> abs(x)
  |
  | [...several other methods...]
  |
  |  ----------------------------------------------------------------------
  |  Data descriptors defined here:
  |
  |  days
  |      Number of days.
  |
  |  microseconds
  |      Number of microseconds (>= 0 and less than 1 second).
  |
  |  seconds
  |      Number of seconds (>= 0 and less than 1 day).

You can see "seconds" there too.
help(datetime.timedelta) or help("datetime.timedelta") work too.

Also, many editors/IDEs have an autocomplete feature: after typing d t .  
the editor may show a list with all known attributes to choose the desired  
name.

-- 
Gabriel Genellina




More information about the Python-list mailing list