Re: problems playing with dates from any month.


krishnakant Mane wrote:
> On 02/08/07, Ian Clark wrote:
>
>> http://docs.python.org/lib/node85.html
>>
> I looked there even before.
> but could not figure out what the code did.
> I know in that variable called s there was a string in a valid date format.
> but when datetime.strptime was used, I did not understand the place
> where a date object say d was created.
> I would expect some thing like d = and the function. but I did not fine that.
> only reference was the datetime module and the documentation is not as good.

>>> import datetime
>>> import time
>>> fmt_string = '29/05/2005'
>>> date_tuple = time.strptime(fmt_string, '%d/%m/%Y')
>>> print date_tuple
(2005, 5, 29, 0, 0, 0, 6, 149, -1)
>>> date_tuple_minus_tz = date_tuple[0:6]
>>> print date_tuple_minus_tz
(2005, 5, 29, 0, 0, 0)
>>> date_obj = datetime.datetime(*date_tuple_minus_tz)

This last line is equivalent to the following:
>>> date_obj = datetime.datetime(2005, 5, 29, 0, 0, 0)
The * in front of a tuple expands it's arguments when making a function call

>>> print date_obj
2005-05-29 00:00:0
>>> print date_obj.day == 5
False

> another question I am getting is that where is the list of all
> formatting characters. like for example Y is 4 digit year M is month
> MM is month in 2 digits etc.
> I am trying to locate a list of all these denoters.
> can you provide me the place

http://docs.python.org/lib/module-time.html

Look for the strptime() function.

>
>
>> Then it's just:
>>
>> if date_obj.day == 5:
>> print 'It's the fifth day of the month'
>>
> this was much better than the documentation, thanks,
> regards,
> Krishnakant.

Hope that helps.

Ian

Posted On: Monday 5th of November 2012 02:18:48 AM Total Views:  174
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




Can't Write to PostGIS PostGreSQL database via psycopg2

I am sort of in a jam here. I am using the PsycoPG2 library to read data out of a windows XP based PostGIS / PostGreSQL database but I am apparently unable to write (update or insert) even though I am able to read (select) I am using PsycoPG2 2.0.6 (psycopg2-2.0.6.win32-py2.5-pg8.2.4- release.exe ) with Python 2.5 (python-2.5.msi) and PostGres 8.2.5.-1 (postgresql-8.2.5-1.zip) and PostGIS 8.2 (postgis-pg82-setup-1.3.1-1.exe) I can use PGadminIII to paste the same SQL queries and execute just fine, but when I try to execute them via python code like import psycopg2 conn = psycopg2.connect("dbname='postgis' user='postgres' host='localhost' password='12345'") c=conn.cursor() c.execute("""INSERT INTO thetable (name) VALUES ('asdf');""") c.execute("""UPDATE thetable SET name = 'somename' WHERE id = 321;""") print(c.statusmessage) #returns "INSERT 0 1" and "UPDATE 0" respectively It gives me very specialized table specific error messages if the query is wrong, but when it's correct, it does nothing and doesn't update. The only way I can update is pasting the query into the PgAdminIII query window. This is a problem on two separate machines (XP and Windows 2003 server) with all of the above components installed by two different people.
VIEWS ON THIS POST

129

Posted on:

Monday 5th November 2012
View Replies!

re: mmm-mode, python-mode and doctest-mode?

On Tue, 7 Aug 2007, Edward Loper wrote: > [John J Lee] >> Is it possible to get doctest-mode to work with mmm-mode and python-mode >> nicely so that docstrings containing doctests are editable in doctest-mode > > I recently released a new version of doctest-mode [1], and I came across your > email [2] (it was on the first page of google hits for "doctest-mode"). So I > decided to have a go at getting doctest-mode to play nicely with mmm-mode. > The result is available here: > > https://python-mode.svn.sf.net/svnro...octest-mode.el Nice! Works for me so far (emacs 22). I'm also very pleased to see that doctest-mode no longer attempts to auto-fill at the end of long lines -- that was extremely annoying, and the new behaviour is a big improvement. Here's another wish. My next-nearest doctest-mode annoyance: hitting TAB should have similar behaviour to python-mode. So, the first press of the TAB key gets you a sensible guess at the indentation you want. The second and subsequent TAB keypresses cycle through no indentation, '>>>' indentation, and '...' indentation. Ideally this would be made to work in combination with the standard indentation-cycling behaviour in those cases where multiple indentations are allowed within Python code (so, it might be ' ... ', '', ' >>> ', ' ... ',' ... ', ' ... ' as the TAB key is repeatedly pressed). >> `doctest-example' >> >> Used to edit doctest examples in text-editing modes, such as >> `rst-mode' or `text-mode'. Docstring submode regions start with >> optionally indented prompts (>>>) and end with blank lines. Use >> (C-c % C-e) to insert a new doctest-example region. When >> `doctest-execute' (C-c C-c) is called inside a doctest-example >> region, it executes all examples in the buffer. I couldn't immediately see how to get this working in a .doctest file, so haven't tried this yet. Another wish: Even though I don't normally run code from emacs directly, I do think it would be very handy indeed to be able to execute a *single* doctest example from doctest-mode. Don't know what keybinding would be conventional... John
VIEWS ON THIS POST

116

Posted on:

Monday 5th November 2012
View Replies!

is there anybody using __del__ correctly??

The title is provocative, of course However, I was browsing through our codebase here at work and I noticed a few usages of __del__ as a resource finalizer (i.e. __del__ just calls a close method). I consider this practice an error, since with __del__ you are never sure that the resource will be released (http://docs.python.org/ref/customization.html#l2h-175) and anyway this should be done with try .. finally or the 'with' statement. So I got into thinking: "yes, using __del__ as a resource finalizer is wrong, but then what are good use cases for it Let's look at the standard library and see what people use __del__ for". So I did, and to my dismay 95% of the __del__ methods in the standard library are just calling a close method!! In particular this happens in the following modules: (Python 2.5 on Ubuntu): zipfile, wave, urllib, close, tarfile, sunau, shelve, httplib, gzip, fileinput, dumbdbm, audiodev, aifc, bsddb.dbshelve, tempfile, socket, platform, ... (I got tired after this point) I see one good use case for __del__ in wsgiref.validate: here __del__ prints a warning if the resource is *not* closed explicitely. Something similar happens in subprocess and popen2, where __del__ updates the list of active processes. So I am beginning to wonder if there exists good use cases for __del__, apart for debugging/checking purposes. Can you provide some Yes, you may take that as a challenge Michele Simionato P.S. BTW, I should mention that if you search comp.lang.python for __del__ you will find hundreds of people who were bitten by __del__, so I usually give advices such as "you should never __del__ in your code". If I am wrong in giving this advice, please let me know! P.P.S. Here and there I hear rumors about deprecating __del__ and nothing happens, are there any news about that Expecially concerning Py3k
VIEWS ON THIS POST

120

Posted on:

Monday 5th November 2012
View Replies!

Re: Adventure-Engines in Python

On 13 aug 2007, at 11.33, Wildemar Wildenburger wrote: > Are there any > > I've set out to make an adventure game and now I'm trying to find a > set > of python-modules to help me do that. I know of the usual non-python > suspects (AGAST, AGS, Wintermute, ...) and while I they are really > good, > I'd like one that is cross platform. > > I've found pyScumm and pyAdv but both don't seem to be ready for use > yet. So are there any "usable" engines written in python > > /W > -- > http://mail.python.org/mailman/listinfo/python-list I don't know of any adventure engines in Python, bet there is an open-source language and class library for text adventures called TADS (www.tads.org) The syntax is similar to C++ and Java. Tads have been ported to ALL major platforms ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren@comhem.se
VIEWS ON THIS POST

129

Posted on:

Monday 5th November 2012
View Replies!

what is the difference between the two kinds of brackets?

hi what is the difference between the two kinds of brackets I tried a few examples but I can't make out any real difference: lst = [10, 20, 30] print lst[0] print lst[2] print lst lst = (10, 20, 30) print lst[0] print lst[2] print lst lst = [10, 20, 40, "string", 302.234] print lst[0:2] print lst[:3] print lst[3:] lst = (10, 20, 40, "string", 302.234) print lst[0:2] print lst[:3] print lst[3:] 10 30 [10, 20, 30] 10 30 (10, 20, 30) [10, 20] [10, 20, 40] ['string', 302.23399999999998] (10, 20) (10, 20, 40) ('string', 302.23399999999998) Are these two kinds of brackets mean the same thing in the "list" context
VIEWS ON THIS POST

133

Posted on:

Monday 5th November 2012
View Replies!

Re: open remote terminal

Hi Steve, Steve Holden wrote: > Fabian Braennstroem wrote: >> >> >> I would like to use python to start an terminal, e.g. xterm, and login on >> a remote machine using rsh or ssh. This could be done using 'xterm -e ssh >> machine', but after the login I would like to jump to a given directory. >> Does anyone have an idea how to do this with python >> >>
VIEWS ON THIS POST

142

Posted on:

Monday 5th November 2012
View Replies!

float to string with different precision

I have to print float numbers to a file. Each float should be 5 characters in width (4 numbers and the decimal point). My problem is that I do not now how to specify float to have different numbers of decimals. For example 5.32 -> 5.320 10.356634 -> 10.357 289.234 -> 289.2 In the string formating operations only fixed number of decimal digits is allow.
VIEWS ON THIS POST

95

Posted on:

Monday 5th November 2012
View Replies!

Gotcha I never ran into before

I've been programming in Python for about 6 years now. One of the features I adore the most is the very useful error messages and stack traces that make it easy to debug. However, today I ran into a difficult to trace bug because the stack trace was reporting the problem in the wrong place. class Delegator(object): def __init__(self, obj): self.obj = obj def __getattr__(self, attr): return getattr(self.obj, attr) class SpecializedDelegator(Delegator): def get_blah(self): return ["Returning Blah"].upper() blah = property(fget=get_blah) print SpecializedDelegator("Doesn't Matter").blah The stack trace is: Traceback (most recent call last): File "test.py", line 12, in print SpecializedDelegator("Doesn't Matter").blah File "test.py", line 5, in __getattr__ return getattr(self.obj, attr) AttributeError: 'str' object has no attribute 'blah' Which is correct, but says nothing about the real problem inside the get_blah method. Is there a good reason that when a property's fget function throws an AttributeError that it should fall back on __getattr__ I would think since the attribute was explicitly defined as a property the property function should be allowed to fully crash and burn. Note: This example is broken up into two classes because that is how I discovered it. Since both classes were in separate files it added to the agony of debugging this. Luckily I was making a small incremental change so I could just back up and figure out what went wrong.
VIEWS ON THIS POST

135

Posted on:

Monday 5th November 2012
View Replies!

problem with Python class creating

Hi all, I have the code like this one: from myMisc import ooIter class MyClass: def __init__(self): pass iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc So it yields "global name 'self' is not defined", that is true. How could I handle the situation Currently I do (and it works, but give me some troubles - I should call MyClass.__init__ for each children class, and there are lots of those ones) class MyClass: def __init__(self): iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc I suspect it has better solution, is it Thank you in advance, Dmitrey
VIEWS ON THIS POST

202

Posted on:

Monday 5th November 2012
View Replies!

How to avoid reverse code engineering of a python executable

Hi guy's, Couple of day's ago I asked for your help on how to create a single file of a python executable. Now I want to proceed a little bit further asking how can I avoid (or at least make it difficult) for some one to extract my code by using reverse code engineer techniques I came on pyobfuscate but I would like more suggestions and guide to achieve the most possible security in this matter.
VIEWS ON THIS POST

176

Posted on:

Monday 5th November 2012
View Replies!

Re: twisted - locking threads when deferToThread is used

And here is the code: from twisted.internet import reactor, defer, threads from siptest import siptest_f from twisted.internet.threads import deferToThread test_opts = {'username':'test','transport':'udp','localport':'5085','password':'test'} domain = ['sip.1und1.de', 'sip.babble.net'] class Getter: def gotResults(self, domain, test_opts): if len(domain) != 0: self.d.callback(siptest_f(domain, test_opts)) else: self.d.errback(ValueError("You used an odd number!")) def _print(self, r, domain): return domain, r def getServerResponse(self, domain, test_opts): self.d = threads.deferToThread(self.gotResults, domain, test_opts) self.d.addCallback(self._print, domain) return self.d def printData(d): print d def printError(failure): import sys sys.stderr.write(str(failure)) def test(): for dom in domain: g = Getter() d = g.getServerResponse(dom, test_opts) d.addCallback(printData) d.addErrback(printError) if __name__ == '__main__': test() reactor.run()
VIEWS ON THIS POST

117

Posted on:

Monday 5th November 2012
View Replies!

Re: Trying to find zip codes/rest example

"VanL" wrote in message news:f8vhct$3g6$1@sea.gmane.org... | | I now cannot find this demo and the associated discussion. Does anybody | remember this demo and where I might be able to find it No, but does the localflavor entry on http://code.djangoproject.com/browse...s.txtrev=5118 help (found with Google)
VIEWS ON THIS POST

191

Posted on:

Monday 5th November 2012
View Replies!

Need recommendations on mock object packages

What are the most popular, easiest to use, and most powerful mock object packages out there
VIEWS ON THIS POST

111

Posted on:

Monday 5th November 2012
View Replies!

[pyserial - winXP] Serial port stop receiving data after a few hours, raise no error

> My soft passively listen to a device sending +- 300 bytes of data each > second. After several hours of work, the soft abruptly stops receiving > data without any error, (while the device sends properly, of course) > and I need to restart it (the python soft) to "reactivate" the ports. > > I read that when the serial port encounters an error (frame error or > so, I imagine) it stop receiving data until the library function > "getCommError()" is called. > > Am I on the good track Can I call this function from my pyserial > code > > Why pyserial does'nt raise a serial.SerialException in this case > > Notes: > --------- > I'm not working with plain serial ports, I use serial over USB (FTDI > or so) and serial over Ethernet (moxa.com). > I'm in 115k 8N1 and I use 4 ports simultaneously > I use python 2.4 with pyserial 2.2 on Windows XP. Late thanks for your both answers! (Please excuse me for that) The problem was a bug in the device firmware. But before finding this, I dugg lightly in the pyserial source and found (to take with care!) : + getCommError(...) is () no more implemented in the win32 API (it was in the win16 API) ; it is replaced by GetCommState(...) ; pyserial use GetCommState(...) in _reconfigurePort() + pyserial use ClearCommError in the functions read(...) and inWaiting(...) ; it takes somewhat different arguments than GetCommState(...) but return the same () info AND clear the errors (getcomm(Error|State) doesn't ()). + the errors on the serial flow (overrun and so) seem just cleared away and not followed to the application by pyserial. PA the links : delta win 16/32 on msdn : http://msdn2.microsoft.com/en-us/library/aa383678.aspx GetCommState() on msdn : http://msdn2.microsoft.com/en-us/library/aa363260.aspx ClearCommError() on msdn : http://msdn2.microsoft.com/en-us/library/aa363180.aspx
VIEWS ON THIS POST

154

Posted on:

Monday 5th November 2012
View Replies!

regexp problem in Python

I want to find "http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11" or 3gp instead of wmv in the text file like this : ""some code"" function reportAbuse() { var windowname="abuse"; var url="/abuse.jsplink=" + "http://www.2shared.com/file/1716611/ e2000f22/Jadeed_Mlak14.html"; OpenWindow = window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500,height=500,left=50,top=50'); OpenWindow.focus(); } function startDownload(){ window.location = "http://www.2shared.com/download/1716611/ e2000f22/Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11"; //document.downloadForm.submit(); } http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.3gptsid=20070803-164051-9d637d11"sfgsfgsfgv I use this pattern : "http.*\.(wmv|3gp).*"" but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ download/1716611/e2000f22/Jadeed_Mlak14.wmv tsid=20070803-164051-9d637d11" what can I do what's wrong whit this pattern thanx for your comments
VIEWS ON THIS POST

150

Posted on:

Monday 5th November 2012
View Replies!

wxWindows - incorrect path on installation?

This should be a very simple one, sorry! I installed wxWindows on my OS X box but I am unable to get my python install to recognize the module. Unfortunately I don't know a whole lot about where modules install to or how to configure python to see them. IE: 'import wx' does not work - it says unknown module wx. Do I need to tweak a path variable or something I have MacPython installed and the binary of wxWindows (wxPython) from wxpython.com
VIEWS ON THIS POST

191

Posted on:

Monday 5th November 2012
View Replies!

Re: Wing IDE for Python v. 3.0 beta1 released

John K Masters wrote: > On 18:23 Wed 01 Aug , Steve Holden wrote: >> Joshua J. Kugler wrote: >>> On Wednesday 01 August 2007 13:53, Robert Dailey wrote: >>>> He's secretly an employee of Wing IDE in disguise!!! >>> Sorry to destroy your conspiracy theories, but no, I've never been employed >>> by Wing IDE in any fashion, nor have I ever received any monetary >>> compensation from them in any form. Just a satisfied user. That's all. >>> >>> j >>> >> Me too, and I have to say the response I have had to all my technical >> support requests has been first-class. Maybe they are busy because >> they're in beta I know they aren't the largest company, but they can >> stand comparison with most when it comes to support. >> >> I can't think of any other products I use where you can contact the >> support team from right inside the software. And get answers without >> paying per-incident support fees! >> >> regards >> Steve >> -- > > I am happy to hear that you have had a good experience with wingide and > I wish I could say the same as I have found the product to be excellent > as far as the concept goes but lacking in the implementation. > > To suggest that, because the autocompletion worked on one method of a > module and not on another was because I had not configured the > PYTHONPATH properly is at least insulting. > >
VIEWS ON THIS POST

166

Posted on:

Monday 5th November 2012
View Replies!

Re: Trying to find zip codes/rest example

Jay Loden wrote: > I don't remember the demo, but a little creative googling turned up > > http://bitworking.org/news/132/REST-...ce-is-infinite > > Which matches the description above perfectly, so I assume it's what you were after :-) That is exactly what I was trying to find! I bow down before your superior google-fu.
VIEWS ON THIS POST

216

Posted on:

Monday 5th November 2012
View Replies!

Representation of new-style instance

Consider a new-style class class rabbit(object): def __init__(self,c): self.color = c r1=rabbit("blue") r2=rabbit("purple") Which C struct in the Python implementation is used to represent the instances c1 and c2 of the new-style class I understand that when the class 'rabbit' is created, the type_new function in typeobject.c creates a copy of a 'struct typeobject' with dictionary tp_dict appropriately modified. However, I can't figure out which structure is used for new-style instances and where the instance dictionary is stored. Could anyone please clarify
VIEWS ON THIS POST

193

Posted on:

Monday 5th November 2012
View Replies!

get directory and file names

I am working with Python 2.5 on Windows XP (SP2). How can I traverse a folder, loop through a list of files and get their file name and extension in an elegant, pythonic way Thank you.
VIEWS ON THIS POST

173

Posted on:

Monday 5th November 2012
View Replies!