TroyGrosfield.com TroyGrosfield.com

Headline

Python Cheat Sheet

Author
by Troy Grosfield
Date
October 17th, 2011
Category
Developer
Story

Frequently used methods I use in Python with examples.

  1. Date and Datetime
  2. Lists and Sets
    1. Finding Intersection of 2 Lists
  3. Working with Urls

Date and Datetime

Useful links:

String to Datetime

Convert a string into a datetime object.

>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
>>> datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
datetime.datetime(2006, 11, 21, 16, 30)

Datetime to String

Convert a datetime object to a string.

from datetime import datetime
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> dt.strftime("%Y-%m-%d %H:%M:%S")
'2006-11-21 16:30:00'
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'

Combine Date and Time

Combine a date and time object into a datetime object.

>>> from datetime import datetime, date, time
>>> datetime.combine(date(2005, 7, 14), time(12, 30))
datetime.datetime(2005, 7, 14, 12, 30)

Find All Dates Between 2 Dates

Find all dates between 2 dates. Uses rrule from python-dateutil.

>>> from dateutil.rrule import *
>>> from dateutil.parser import *
>>> from datetime import *
>>>
>>> list(rrule(DAILY,
...            dtstart=datetime(2012, 1, 20),
...            until=datetime(2012, 1, 23)))
[datetime.datetime(2012, 1, 20, 0, 0), 
 datetime.datetime(2012, 1, 21, 0, 0), 
 datetime.datetime(2012, 1, 22, 0, 0), 
 datetime.datetime(2012, 1, 23, 0, 0)]

Lists and Sets

Intersection

Find all elements that exist in both lists.

>>> vals1 = ['hello','test','example','world']
>>> vals2 = ['trying','to','testing','hello','world']
>>> set(vals1).intersection(vals2)
set(['world', 'hello'])

Difference

Find all distinct elements from one list to another.

>>> vals1 = [1,2,4,5]
>>> vals2 = [2,5,7,8,9]
>>> set(vals1).difference(vals2)
set([1, 4])
>>> set(vals2).difference(vals1)
set([7, 8, 9])

Working with Urls

Url Concatenation

Concatenate two string to form a url.

>>> from urlparse import urljoin
>>> urljoin('http://google.com/','/hello/world.html')
'http://google.com/hello/world.html'
>>> urljoin(u'http://google.com/',u'/hello/world.html')
u'http://google.com/hello/world.html'

Url Encoding

Encoding a dictionary to a query param string:

>>> from urllib import urlencode
>>> d = {'hello': 'my value',
...      'world': 'another value'}
>>> urlencode(d)
'world=another+value&hello=my+value'

Quote and Unqote Urls

>>> import urllib
>>> url = 'http://troygrosfield.com/some-page/testing?h=hello&w=world'
>>> urllib.quote(url)
'http%3A//troygrosfield.com/some-page/testing%3Fh%3Dhello%26w%3Dworld'
>>> urllib.unquote(url)
'http://troygrosfield.com/some-page/testing?h=hello&w=world'

Url Parsing

Parse a url to get all of the url segments.

>>> import urlparse
>>> url = urlparse.urlsplit('http://www.troygrosfield.com/hello/world/testing?h=hello&w=world#anchor-jump')
SplitResult(scheme='http',
            netloc='www.troygrosfield.com',
            path='/hello/world/testing',
            query='h=hello&w=world',
            fragment='anchor-jump')
>>> url.scheme
'http'
>>> url.netloc
'www.troygrosfield.com'
>>> url.path
'/hello/world/testing'
>>> url.query
'h=hello&w=world'
>>> url.fragment
'anchor-jump'

Printing All Attributes and Values in an Object

Sometime you want to know what attributes and values are in an object.  The example below is not django specific, the User model just has the required __dict__ attr:

>>> from pprint import pprint
>>> from django.contrib.auth.models import User
>>>
>>> user = User.objects.create_user(username='test', 
...                                 first_name='Troy', 
...                                 last_name='Grosfield')
>>> pprint(vars(user))
{'_profile_cache': <Profile: Profile object>,
 '_state': <django.db.models.base.ModelState object at 0x35b02d0>,
 'date_joined': datetime.datetime(2013, 4, 25, 20, 41, 3, 176637),
 'email': u'',
 'first_name': u'Troy',
 'id': 1,
 'is_active': True,
 'is_staff': False,
 'is_superuser': False,
 'last_login': datetime.datetime(2013, 4, 25, 20, 41, 3, 176637),
 'last_name': u'Grosfield',
 'password': u'!',
 'username': 'test'}

Note: The object you’re trying to print must have the __dict__ attribute or you will get an error that looks something like:

>>> from pprint import pprint
>>> from datetime import datetime
>>>
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2013, 4, 25, 20, 46, 29, 493743)
>>> pprint(vars(dt))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
Tags
Comments
No Comments »

No Comments Yet

Leave a reply