0

Possible Duplicate:
Convert Date String to DateTime Object in Python

Is there an easy way to convert the string the string 10/22/1984 into a datetime.date object?

Community
  • 1
  • 1
David542
  • 104,438
  • 178
  • 489
  • 842

4 Answers4

4

You can use datetime.strptime method for this purpose:

from datetime import datetime

dVal = datetime.strptime('10/22/1984', '%m/%d/%Y')

You can read more using the following link that describes python strptime behavior.

Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
1

Yes.

>>> datetime.datetime.strptime("10/22/1984", "%m/%d/%Y")
datetime.datetime(1984, 10, 22, 0, 0)
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

I'm sure there are many easy ways. Here is one:

import re
import datetime

my_date = '10/22/1984'
date_components = re.compile(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)')
matched_date_components = date_components.match(my_date)
date_time_object = datetime.date(year=matched_date_components.year,
                                 month=matched_date_components.month,
                                 day=matched_date_components.day)
Profane
  • 1,128
  • 8
  • 13
  • Looking at the other answers, I apparently was confused and thought the question asker wanted "a complicated way" not "an easy way." But hey, with the success of "learn python the hard way," maybe I'll get some sympathy up votes from hardcore hardwayers. – Profane Aug 12 '11 at 13:13
  • 1
    Here is my sympathy up vote. +1 – Fábio Diniz Aug 12 '11 at 13:50
0

first import datetime and then try in will work.

from datetime import datetime date = datetime.strptime('10/22/1984', '%d/%m/%y')