Python Tutorial

Friday, July 22, 2011

Python:Url Fetch

Python URL Request Response
Some times when we try to fetch url directly server does not return page content. For this reason we need to request the server first then read the page using this response. A sample code of python request response is given below.
We can also set some others additional parameter as timeout, max redirect so on
import urllib2
def get_url_content(site_url):
    rt=""
    try:
        request = urllib2.Request(site_url) 
        f=urllib2.urlopen(request)
        content=f.read()
        f.close()
    except urllib2.HTTPError, error:
        content=str(error.read())
    return content

Thursday, July 21, 2011

Date time

Python date time comparison:
For python date time comparison you can directly compare between two date and also make some mathematical operation
import datetime
import time
before=datetime.datetime.now()
print "before "+str(before)
time.sleep(5)
after=datetime.datetime.now()
print "after "+str(after)
difference=after-before
print "difference "+str(difference)



before 2011-07-21 15:38:13.330000
after 2011-07-21 15:38:18.347000
difference 0:00:05.017000

String split by length

Python String split by length:
some time we need to split string by length, sample code is given below

def split_by_length(s,block_size):
    w=[]
    n=len(s)
    for i in range(0,n,block_size):
        w.append(s[i:i+block_size])
    return w
w=split_by_length("ABCDEFGHIJKLMNOPQRSTUVWXYZ",5)
print w




Output:

['ABCDE', 'FGHIJ', 'KLMNO', 'PQRST', 'UVWXY', 'Z']