1

I have a String, Sent: Fri Sep 18 00:30:12 2009 that I want to turn into a Python date object.

I know there's a strptime() function that can be used like so:

>>> dt_str = '9/24/2010 5:03:29 PM'
>>> dt_obj = datetime.strptime(dt_str, '%m/%d/%Y %I:%M:%S %p')
>>> dt_obj
datetime.datetime(2010, 9, 24, 17, 3, 29)

Can anybody think of an easier way to accomplish this than going through a bunch of conditionals to parse out if Sep, month = 9?

2 Answers 2

1

To parse rfc 822-like date-time string, you could use email stdlib package:

>>> from email.utils import parsedate_to_datetime
>>> parsedate_to_datetime('Fri Sep 18 00:30:12 2009')
datetime.datetime(2009, 9, 18, 0, 30, 12)

This is Python 3 code, see Python 2.6+ compatible code.

You could also provide the explicit format string:

>>> from datetime import datetime
>>> datetime.strptime('Fri Sep 18 00:30:12 2009', '%a %b %d %H:%M:%S %Y')
datetime.datetime(2009, 9, 18, 0, 30, 12)

See the table with the format codes.

0

Use the python-dateutil library!

First: pip install python-dateutil into your virtual-env if you have one then you can run the following code:

from dateutil import parser

s = u'Sent: Fri Sep 18 00:30:12 2009'
date = parser.parse(s.split(':', 1)[-1])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.