Response - convert date to epoch

December 29, 2010 at 12:45 PM | categories: python | View Comments

I ran across Sandro Tosi's post about converting a date to epoch and for what ever reason blogger wasn't letting me leave comments so I figured I'd toss this post up. I just had to do this very same thing in one of my projects.

>>> import time, calendar
>>> ts = time.strptime('2010-12-01', '%Y-%m-%d')
>>> calendar.timegm(ts)
1291161600
>>> ts = time.strptime('1970-01-01', '%Y-%m-%d')
>>> calendar.timegm(ts)
0

So there you have it. Thank you calendar module!

Read and Post Comments

City and state lookup from zipcode

December 29, 2010 at 11:53 AM | categories: python | View Comments

We wanted to be able to present the user with an input box for their zip and then determine the city state for that zipcode. We don't care about city aliases we just want to get the proper city name. I was given a file from zip-codes.com and told to make it so. This was going to be rather simple and boring. Part of the requirement was to have a tuple returned that contained city, state, short state, and zip code when doing lookups. The other part was easily handling the infrequent updates. After looking at the sample data and determining that their main file is CSV but all of their updates are sent out at Tab delimited. Honestly that made me happy because it was great excuse to use csv.Sniffer. So here is the Django model I ended up with.

from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from csv import Sniffer, DictReader

# Not sold on this name, but couldn't think of a better one.
class Location(models.Model):
    """
    location / zipcode lookup table
    """

zipcode = models.CharField(max_length=5, unique=True, db_index=True)
    city = models.CharField(max_length=150)
    state = models.CharField(max_length=150)
    state_abbrv = models.CharField(max_length=2)

@classmethod
    def load(cls, filename):
        """
        reads filename, attempts to determine if it is comma or tab delimited
        creates or updates records based on ZipCode and PrimaryRecord key pair
        the following fields must exist in the file: ZipCode, PrimaryRecord,
        CityMixedCase, StateFullName, State
        """

csv_fd = open(filename, 'r')

# grab the header for Sniffer
        # reset the position back to the start of the file
        csv_header = csv_fd.readline()
        csv_fd.seek(0)

# determine if we are CSV or Tab delimited
        dialect = Sniffer().sniff(csv_header)
        csv_dict = DictReader(csv_fd, dialect=dialect)

for row in csv_dict:
            if row['PrimaryRecord'] == "P":
                zipcode = row['ZipCode']
                ZL, created = cls.objects.get_or_create(zipcode=zipcode)
                ZL.zipcode = zipcode
                ZL.city = row['CityMixedCase']
                ZL.state = row['StateFullName']
                ZL.state_abbrv = row['State']
                ZL.save()

@classmethod
    def lookup(cls, zipcode):
        """
        given a zipcode will lookup, populate, and return a tuple with
        city, state, zip information else return unavailable and searched zipcode
        """

try:
            zl = cls.objects.get(zipcode=zipcode)
            return (zl.city, zl.state, zl.state_abbrv, zipcode)
        except ObjectDoesNotExist:
            return (('unavailable',) * 3) + (zipcode,)

Read and Post Comments

Looking for Work

December 28, 2010 at 02:00 PM | categories: python | View Comments

I am looking for telecommute work. With Jessica starting graduate school, which involves a lot of traveling and moving, I won't be able to have an on-site nine to five for the next couple years. I am interested in full-time telecommute and part-time 1099 contract work. If you or someone you know is looking for people, let me know or pass my information along. Here is my CV.

Read and Post Comments

Random IP Address in Python

December 22, 2010 at 06:44 PM | categories: python | View Comments

I needed to generate a random IP address for some testing with Google Maps API. Using GeoIP to place a pin when users of a site interact with it. The site is based in the US and will only have US users. I have a list of network ranges from MaxMind in a file. I want to randomly select a network and then randomly select an IP address from that network so the functional testing for the Google Maps and GeoIP integration is a bit more robust. The solution was a nice little algorithm from a SO question and the using the ipaddr library.

# randomly select a line from the file
import random

def random_line(afile):
    line = next(afile)
    for num, aline in enumerate(afile):
        if random.randrange(num + 2): continue
        line = aline
 return line

Then once I have that line, I feed it in to ipaddr and select a random IP address from the network. This is done using randrange and with the fact the ipaddr supports int casting for IP addresses.

    
import ipaddr

network = ipaddr.IPv4Network(random_line(open('networks.txt')))
randmon_ip = ipaddr.IPv4Address(random.randrange(int(network.network) + 1,
                                                 int(network.broadcast) - 1))

Read and Post Comments

Migrating to Blogofile

December 16, 2010 at 03:23 PM | categories: personal | View Comments

Because I am a lemming and everyone else is doing it, I too am going to migrate to blogofile! Then I'll blog about doing it!

Read and Post Comments

Next Page ยป