Skip to content

Instantly share code, notes, and snippets.

@schwanksta
Created May 5, 2010 00:10
Show Gist options
  • Save schwanksta/390215 to your computer and use it in GitHub Desktop.
Save schwanksta/390215 to your computer and use it in GitHub Desktop.
Converts an AP Style date string to a Python datetime object.
def apdate_to_datetime(date):
"""
Takes an AP-formatted date string and returns a Python datetime
object. This will also work on any date formatted as either
'%b. %d, %Y' or '%B %d, %Y'
Examples:
>>> apdate_to_datetime("Sept. 4, 1986")
datetime.datetime(1986, 9, 4, 0, 0)
>>> apdate_to_datetime("Sep. 4, 1986")
datetime.datetime(1986, 9, 4, 0, 0)
>>> apdate_to_datetime("September 4, 1986")
datetime.datetime(1986, 9, 4, 0, 0)
"""
from datetime import datetime as dt
if date.startswith('Sept.'):
date = date.replace('Sept.', 'Sep.')
try:
datetime_date = dt.strptime(date, "%b. %d, %Y")
except ValueError:
datetime_date = dt.strptime(date, "%B %d, %Y")
return datetime_date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment