Parsing dates in Python

One of those weird things that always slips my mind and always seems less obvious than it should be.

Parsing a date (object) from a string representation in Python seems oddly neglected or cumbersome as compared to the rest of the standard library that surrounds it. (Witness the number of date utility libraries available.) Anyway, here's a brief recap for those of you googling "python parsing date", like I do so very often:

def str2date (str, fmt):
        """
        Return a date from a string in a given format.
        Params:
                - str: a string representing a date (e.g. "2009-12-25")
                - fmt: a strptime/strftime style format (e.g. "%Y/%m/%d")

        Example::

                str2date ("2009-12-25", "%Y-%m-%d")
        """
        from datetime import datetime
        return datetime.strptime (st), fmt).date()

Tricks:

  1. You can't produce a date (object) from a date (string), but you can produce a datetime object and use it to make a date string.
  2. It's the datetime class not the datetime module
  3. strptime, really?