18

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

0

3 Answers 3

50

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)
Sign up to request clarification or add additional context in comments.

Comments

5

This should work:

import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))

2 Comments

python has built in methods that handles doing this
Oops, forgot about str to int. I don't frequently use datetime, so I'm glad that there's a better way to do this.
4
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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.