Created
May 5, 2010 00:10
-
-
Save schwanksta/390215 to your computer and use it in GitHub Desktop.
Converts an AP Style date string to a Python datetime object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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