1

Possible Duplicate:
Parsing Dates and Times from Strings using python

I'm reading a string

"2011-06-11"

How can I cast this to a date object?

thanks

Community
  • 1
  • 1
bb2
  • 2,872
  • 7
  • 37
  • 45

4 Answers4

4

If you know it will be in that format, you can use the strptime function:

datetime.datetime.strptime(s, "%Y-%m-%d").date()

(and it's not a cast, you're actually creating a new date out of the string)

If you don't know the format of the date, I suggest looking at the dateutil module which provides a powerful date parsing function.

David Z
  • 128,184
  • 27
  • 255
  • 279
  • 1
    I know, but it's a static method which doesn't take a class parameter, so it's called the same way as a non-member function. I thought it easier to just call it a function. (Plus technically there _is_ an actual Python function at work behind the scenes.) – David Z Oct 31 '11 at 20:53
1
In [105]: import datetime as dt

This parses the string and returns a dt.datetime object:

In [106]: dt.datetime.strptime('2011-06-11',"%Y-%m-%d")
Out[106]: datetime.datetime(2011, 6, 11, 0, 0)

This returns a dt.date object:

In [108]: dt.datetime.strptime('2011-06-11',"%Y-%m-%d").date()
Out[108]: datetime.date(2011, 6, 11)

The strptime method is documented here, and the format string "%Y-%m-%d" is explained here.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Do this:

import datetime

date = datetime.datetime.strptime('2011-06-11', '%Y-%m-%d')
César
  • 9,939
  • 6
  • 53
  • 74
0
datetime.datetime.strptime("2011-06-11", "%Y-%m-%d")

Also check out How to parse an ISO 8601-formatted date?

Community
  • 1
  • 1
wmil
  • 3,179
  • 2
  • 21
  • 24