Re: How to get milliseconds when substructing datetime objects?
*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.00 This means that time difference between d2 and d1 is 1 day 23 hours 50 minutes 0 seconds and 00 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%3FIn-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': , '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
Re: How to get milliseconds when substructing datetime objects?
While looking for ready to use library I have roughly skteched the functions that I need: import datetime from datetime import * def timedelta2Micros(dt): Convert timedelta object to micriseconds days = dt.days sec = dt.seconds micros = dt.microseconds daysSec = 24 * 60 * 60 * days tdMicros = (daysSec + sec) * 100 + micros return tdMicros def micros2timedelta(micros): Convert microseconds to timedelta oneDayMicros = 24 * 60 * 60 * 100 days = micros / oneDayMicros # whole number of days scrapDayMicros = micros % oneDayMicros # remainder of all micros in a day secs = scrapDayMicros / 100 # whole number of seconds micros = scrapDayMicros % 100 # micros left return timedelta(days=days, seconds=secs, microseconds=micros) In case somebody have a library with *extra* datetime functions (and better written then these ones) please let me know! -- Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr *Dmitri O.Kondratiev* dokondr at gmail.compython-list%40python.org?Subject=How%20to%20get%20milliseconds%20when%20substructing%20datetime%20objects%3FIn-Reply-To=wrote: *Thu Dec 13 16:19:35 CET 2007* - Previous message: to Doctest as SystemExit is to Python http://mail.python.org/pipermail/python-list/2007-December/469615.html - Next message: Question from a python newbie http://mail.python.org/pipermail/python-list/2007-December/469631.html - *Messages sorted by:* [ date ]http://mail.python.org/pipermail/python-list/2007-December/date.html#469626 [ thread ]http://mail.python.org/pipermail/python-list/2007-December/thread.html#469626 [ subject ]http://mail.python.org/pipermail/python-list/2007-December/subject.html#469626 [ author ]http://mail.python.org/pipermail/python-list/2007-December/author.html#469626 -- *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.00 This means that time difference between d2 and d1 is 1 day 23 hours 50 minutes 0 seconds and 00 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%3FIn-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
How to get milliseconds when substructing datetime objects?
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) - Thanks! -- Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr -- http://mail.python.org/mailman/listinfo/python-list
Millisecond timestamp function?
What Python module / function can be used to get millisecond timestamps? time.time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. Thanks! -- Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbi Q: What is a rational for strings not being lists in Python?
On 10/16/07, Matt McCredie [EMAIL PROTECTED] wrote: [quote] The example you posted won't work with tuples either because they, like strings, are also immutable. So, the best way to get the posted code to work (which is a bad way to go about reversing a string, but I digress) [end-quote] I agree, my first example: def reverse1(xs): if xs == []: return xs else: return (reverse1 (xs[1:])) + [xs[0]] is very inefficient. I posted it just to illustrate my question about strings and lists in Python. The cost of reverse1() is proportional to: (N - 1) + (N -2) + ...+1 = N(N - 1) /2, which in turn is ~ square(N), where N is the number of elements in the list. For example, reverse2() demonstrates a better algorithm, with cost proportional to N: def head(xs) : if xs == []: return [] else: return xs[0] def tail(xs) : if xs == []: return [] else: return xs[1:] def addHead (acc, xs): if xs == []: return acc else: return addHead ([head(xs)] + acc, tail(xs)) def reverse2 (xs): if xs == []: return [] else: return addHead([], xs) [quote] is to cast the input parameter to a list first. The returned value will always be a list, but you will simply have to convert it back to the appropriate type when you are done. [end-quote] Casting and writing wrapper classes is not interesting. Life becomes much easier when String is a subtype of List, and when you have polymorphic functions making no difference between String and List. [quote] What is the purpose if immutability? It allows a value to be hashed. I don't want to get into a discussion about methods for hashing mutable types, if you are interested just do a search on the list archives. Hashing allows for quick comparisons of values, but more importantly it allows for values to be used as keys for the dict type. This is very important because, as you will soon find out if you keep learning the language, all namespaces in python are implemented as dicts. [end-quote] As for me, I am perfectly happy with immutable types, I would rather do without mutable ones. And thanks, everybody, for reminding me that Python is a 'side effect' language, from which by definition follows that it should have mutable lists along with immutable strings. So answer to my question What is a rational for strings not being lists in Python? is quite trivial, as Simon B. ([EMAIL PROTECTED]) [EMAIL PROTECTED]wrote: Lists are mutable, strings are not, so so strings can't support all a list's methods. Sorry again for trivial question :(worked too much with Haskell recently and mostly forgot about mutable types , I guess ) ... [quote] So... if you want a mutable string, just cast it to a list, do your operations and cast it back to a string. Incidentally, the proper method for converting a list of characters to a string is by using the join method on an empty string. s = I am a string x = list(s) x ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g'] .join(x) 'I am a string' Matt [end-quote] -- Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr -- http://mail.python.org/mailman/listinfo/python-list
Using Python to access CORBA server?
Need advice: What library can Python client use to access CORBA server using DII (Dynamic Invocation Interface) ? Thanks, Dima -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbi Q: Recursively reverse lists but NOT strings?
Gary, thanks for lots of info! Python strings are not lists! I got it now. That's a pity, I need two different functions: one to reverse a list and one to reverse a string: def reverseList(xs): if xs == []: return xs else: return (reverseList (xs[1:])) + [xs[0]] def reverseStr(str): if str == : return str else: return (reverseStr (str[1:])) + str[0] Ok. Now regarding in-place reversal of a list: l = [1,2,3] l [1, 2, 3] l.reverse() l [3, 2, 1] That was, as I expected. Good. Then why this ? : ls = [1,2,3].reverse() ls print [1,2,3].reverse() None I mean, why ls is empty after assignment? Also, I couldn't find in the Python docs what this form of slicing means: xs[::-1] ? It works for creating a reversed copy of either a string or a list, but what does '::-1' syntax means? Thanks, Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr On 10/15/07, Gary Herron [EMAIL PROTECTED] wrote: Dmitri O.Kondratiev wrote: The function I wrote (below) reverses lists all right: def reverse(xs): if xs == []: return [] else: return (reverse (xs[1:])) + [xs[0]] reverse ([1,2,3]) [3, 2, 1] Yet when I try to reverse a string I get: reverse (abc) ... ... ... File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 2, in reverse if xs == []: RuntimeError: maximum recursion depth exceeded in cmp What's wrong? Why recursion never stops? If you are doing this as an python-learning exercise, then read on. If you are doing this reversal for real code, then try: xs.reverse() for in-place reversal of a list (but not a string), or result = xs[::-1] for creating a reversed copy of either a string or a list Your recursion stops when xs == [], but when you're stripping characters off a string, like 'abc', the remaining portion will be 'bc', then 'c', than '', but never [] so you 'll never stop. Try: if xs == []: return [] elif xs == '': return '' else: ... Gary Herron Thanks, Dima -- http://mail.python.org/mailman/listinfo/python-list
Newbi Q: What is a rational for strings not being lists in Python?
To clarify my point: reverse() is a lucky one - Python has variants of *this particular* function both for lists and strings. Yet what about other list functions? How in general, can I write a function that works both on list and string types? Both are sequences, right? Why string is not a subtype of a list then? The advantage of string being a list of elements, where element is a char is that all list functions will work *without any modifications* on strings as well as on other types of lists. So, I am trying to understand: what is a rational for strings not being lists in Python? Thanks, -- Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr On 10/15/07, Dmitri O.Kondratiev [EMAIL PROTECTED] wrote: Gary, thanks for lots of info! Python strings are not lists! I got it now. That's a pity, I need two different functions: one to reverse a list and one to reverse a string: def reverseList(xs): if xs == []: return xs else: return (reverseList (xs[1:])) + [xs[0]] def reverseStr(str): if str == : return str else: return (reverseStr (str[1:])) + str[0] Ok. Now regarding in-place reversal of a list: l = [1,2,3] l [1, 2, 3] l.reverse() l [3, 2, 1] That was, as I expected. Good. Then why this ? : ls = [1,2,3].reverse() ls print [1,2,3].reverse() None I mean, why ls is empty after assignment? Also, I couldn't find in the Python docs what this form of slicing means: xs[::-1] ? It works for creating a reversed copy of either a string or a list, but what does '::-1' syntax means? Thanks, Dmitri O. Kondratiev [EMAIL PROTECTED] http://www.geocities.com/dkondr On 10/15/07, Gary Herron [EMAIL PROTECTED] wrote: Dmitri O.Kondratiev wrote: The function I wrote (below) reverses lists all right: def reverse(xs): if xs == []: return [] else: return (reverse (xs[1:])) + [xs[0]] reverse ([1,2,3]) [3, 2, 1] Yet when I try to reverse a string I get: reverse (abc) ... ... ... File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 2, in reverse if xs == []: RuntimeError: maximum recursion depth exceeded in cmp What's wrong? Why recursion never stops? If you are doing this as an python-learning exercise, then read on. If you are doing this reversal for real code, then try: xs.reverse() for in-place reversal of a list (but not a string), or result = xs[::-1] for creating a reversed copy of either a string or a list Your recursion stops when xs == [], but when you're stripping characters off a string, like 'abc', the remaining portion will be 'bc', then 'c', than '', but never [] so you 'll never stop. Try: if xs == []: return [] elif xs == '': return '' else: ... Gary Herron Thanks, Dima -- http://mail.python.org/mailman/listinfo/python-list
Newbi Q: Recursively reverse lists but NOT strings?
The function I wrote (below) reverses lists all right: def reverse(xs): if xs == []: return [] else: return (reverse (xs[1:])) + [xs[0]] reverse ([1,2,3]) [3, 2, 1] Yet when I try to reverse a string I get: reverse (abc) ... ... ... File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 5, in reverse return (reverse (xs[1:])) + [xs[0]] File C:\wks\python-wks\reverse.py, line 2, in reverse if xs == []: RuntimeError: maximum recursion depth exceeded in cmp What's wrong? Why recursion never stops? Thanks, Dima -- http://mail.python.org/mailman/listinfo/python-list