How to get milliseconds when substructing datetime objects?

Dmitri O.Kondratiev dokondr at gmail.com
Thu Dec 13 10:19:35 EST 2007


*Gabriel thanks for detailed info!
Actually I have already went the same (only more limited :) way as you
suggested  and did some poking with dir() at datetime and timedelta objects.

This time I have bumped into the following problems that I can't find ready
solutions yet:

Subtracting of datetime objects results in timedelta object, so:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
print "Time difference: "+ str(dt)

Will output:
Time difference: 1 day, 23:50:00.999900

This means that time difference between d2 and d1 is 1 day 23 hours 50
minutes 0 seconds and 999900 microseconds.

Ok, looks nice and useful! Yet questions remain:

Are there any standard Python library functions that:
1) Convert timedelata object to micro- or milliseconds?
2) Convert timedelata object to datetime object?
3) Convert datetime object to milli- or microseconds? So I could do
something like this:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
dt.milliseconds()

and also this:

t1 = datetime.datetime.now()
millis = t1.milliseconds()

Thanks!
Dima

**Gabriel Genellina* gagsl-py2 at yahoo.com.ar
<python-list%40python.org?Subject=How%20to%20get%20milliseconds%20when%20substructing%20datetime%20objects%3F&In-Reply-To=>
*Thu Dec 13 00:13:22 CET 2007*

   - Previous message: How to get milliseconds when substructing datetime
   objects?
   <http://mail.python.org/pipermail/python-list/2007-December/469397.html>
   - Next message: Solve a graphical problem about different logos with a
   script
   <http://mail.python.org/pipermail/python-list/2007-December/469399.html>
   - *Messages sorted by:* [ date
]<http://mail.python.org/pipermail/python-list/2007-December/date.html#469507>
[
   thread ]<http://mail.python.org/pipermail/python-list/2007-December/thread.html#469507>
[
   subject ]<http://mail.python.org/pipermail/python-list/2007-December/subject.html#469507>
[
   author ]<http://mail.python.org/pipermail/python-list/2007-December/author.html#469507>

------------------------------

En Wed, 12 Dec 2007 11:40:24 -0300, Dmitri O.Kondratiev
<dokondr at gmail.com
<http://mail.python.org/mailman/listinfo/python-list>> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071213/97693754/attachment.html>


More information about the Python-list mailing list