17
votes

How do I convert a string to a date object in python?

The string would be: "30-01-12" (corresponding to the format: "%d-%m-%y")

I don't want a datetime.datetime object, but rather a datetime.date

3

3 Answers

47
votes

You still use datetime.datetime but then request just the .date() portion:

datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()

Demonstration:

>>> import datetime
>>> datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
datetime.date(2012, 1, 30)
4
votes

This should work:

import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))
4
votes
from datetime import datetime,date
date_str = '30-01-12'
formatter_string = "%d-%m-%y" 
datetime_object = datetime.strptime(date_str, formatter_string)
date_object = datetime_object.date()