coolbeans
coolbeans

Reputation: 31

Turn a String into a Python Date object

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?

Upvotes: 1

Views: 61

Answers (2)

jfs
jfs

Reputation: 414225

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.

Upvotes: 1

noseworthy
noseworthy

Reputation: 46

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])

Upvotes: 0

Related Questions