Daily Grind 1: Python Problems & Solutions

Daily Grind 1: Python Problems & Solutions

To start things off I am tossing out a few python problems I have come across recently, and the solutions I found for them.

Python Date Manipulation

While creating a python integration for MailChimp I needed to create a SQL query that would grab all records of a certain type that were created since Friday of last week.  If you have spent any time in the land of PHP, the strtotime method may come to mind.  Python even has a port of that module that would allow me to do something like this:

from timelib import strtodatetime
strtodatetime('last friday')

Unfortunately, I had problems getting timelib to work with python3 in a reasonable amount of time.  I decided to go with a different solution:

from datetime import datetime, timedelta
friday = (datetime.today() - 
  timedelta(days=datetime.today().weekday()) + 
  timedelta(days=4, weeks=-1))
print(friday.strftime("%Y-%m-%d"))

This solution isn’t quite as succinct, but it works.  The datetime lib also seems to be a bit more widely used – so it feels like this solution would be a little more generally accepted vs. the sort of one-off solution timelib provides.  If there is any confusion:

  • datetime.today() gets today’s date
  • timedelta(days=datetime.today().weekday()) effectively subtracts the number of days passed so far in this week
  • timedelta(days=4, weeks=-1) subtracts one week, adds 4 days – leaving us with Friday

Python MailChimp Integration

Meanwhile, the rest of the MailChimp integration was pretty straight forward.  I used an existing python3 library that got me 90% of the way there.  There were only a few hiccups, which I will go over below.  Here is the code snippet that covers the general process of using the lib to add a new subscriber to a list:

try:
  hash = get_subscriber_hash(email)
  response = client.lists.members.create_or_update(LIST_ID, hash, {
    'email_address': email,
    'status_if_new': 'subscribed',
    'merge_fields': {
      'FNAME': first_name,
      'LNAME': last_name
    }
  });
except HTTPError as err:
  print('Error adding subscriber: ' + str(err))
  print(err.response.json())
except ValueError as err:
  print(err)

At first I tried to use the client.lists.members.create method, but quickly ran into errors when the subscriber was already on the list.  The create_or_update method will automatically add the subscriber if it doesn’t already exist, or just update the merge fields if it does.  For this method, it is necessary to pass a value for status_if_new, as well as the hash for the subscriber.  I found a get_subcriber_hash helper function in the library which looks like it basically just md5s the email address.  The method also runs a generic check against the email address to try and make sure it’s valid.  It doesn’t seem to catch everything that the actual MailChimp API does, however, so I wrapped the entire block in a try/except to deal with the errors.

 

Leave a Reply

Your email address will not be published. Required fields are marked *