-2
s = "June 19, 2010"

How do I conver that to a datetime object?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
TIMEX
  • 238,746
  • 336
  • 750
  • 1,061

4 Answers4

2

There's also the very good dateutil library, that can parse also stranger cases:

from dateutil.parsers import parse
d = parse(s)
pygabriel
  • 9,670
  • 4
  • 39
  • 54
1

Use datetime.strptime. It takes the string to convert and a format code as arguments. The format code depends on the format of the string you want to convert, of course; details are in the documentation.

For the example in the question, you could do this:

from datetime import datetime
d = datetime.strptime(s, '%B %d, %Y')
David Z
  • 122,461
  • 26
  • 246
  • 274
0

As of python 2.5 you have the method datetime.strptime(): http://docs.python.org/library/datetime.html

dt = datetime.strptime("June 19, 2010", "%B %d, %Y")

if your locale is EN.

relet
  • 6,562
  • 2
  • 31
  • 41
0

Use datetime.datetime.strptime:

>>> import datetime
>>> s = "June 19, 2010"
>>> datetime.datetime.strptime(s,"%B %d, %Y")
datetime.datetime(2010, 6, 19, 0, 0)
msanders
  • 5,499
  • 1
  • 27
  • 30