Is there a easier mechanism to parse arbitrary date strings in several different formats in Python?

I was in-need of parsing a date string value returned by PostgreSQL into something that can be manipulated in Python. After several hours of searching, I found a mechanism to accomplish this and have documented it here to help others who may encounter a similar situation in future.

# Install the python-dateutil library.

# In virtualenv environments:
pip install python-dateutil

# If you prefer to install system wide:
sudo pip install python-dateutil

# If you are using Ubuntu or an Ubuntu derived OS:
sudo apt-get install python-dateutil

# After installation, fire up the Python terminal and import dateutil parser.

>>>from dateutil.parser import parse
>>>parse("2012-08-16 14:25:05.265739")
datetime.datetime(2012, 8, 16, 14, 25, 5, 265739)

# The parse command converted the date time string into a valid datetime object.

Checkout http://labix.org/python-dateutil for more examples.


References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s