How do I convert String into Date object

Peter Otten __peter__ at web.de
Sat Aug 13 16:29:35 EDT 2011


MrPink wrote:

> I have file of records delimited by spaces.
> I need to import the date string and convert them into date datatypes.
> 
> '07/27/2011' 'Event 1 Description'
> '07/28/2011' 'Event 2 Description'
> '07/29/2011' 'Event 3 Description'
> 
> I just discovered that my oDate is not an object, but a structure and
> not a date datatype.
> I'm stumped.  Is there a way to convert a string into a date datatype
> for comparisons, equality, etc?
> 
> Thanks,
> 
> On Aug 13, 3:14 pm, MrPink <tdsimp... at gmail.com> wrote:
>> Is this the correct way to convert a String into a Date?
>> I only have dates and no time.
>>
>> import time, datetime

That looks like a fifty-percent chance to try the "wrong" module ;)

>> oDate = time.strptime('07/27/2011', '%m/%d/%Y')
>> print oDate

>>> import datetime as dt
>>> d = dt.date.strptime("07/27/2011", "%m/%d/%Y")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.date' has no attribute 'strptime'

So you cannot construct a date from a date string either. 
One more time:

>>> d = dt.datetime.strptime("07/27/2011", "%m/%d/%Y")
>>> d
datetime.datetime(2011, 7, 27, 0, 0)
>>> d.date()
datetime.date(2011, 7, 27)

$ cat csv_dates.csv
'07/27/2011' 'Event 1 Description'
'07/28/2011' 'Event 2 Description'
'07/29/2011' 'Event 3 Description'
$ cat csv_dates.py
import datetime
import csv

def rows(instream):
    for row in csv.reader(instream, delimiter=" ", quotechar="'"):
        row[0] = datetime.datetime.strptime(row[0], '%m/%d/%Y').date()
        yield row

if __name__ == "__main__":
    import sys
    filename  = sys.argv[1]

    with open(filename, "rb") as instream:
        for row in rows(instream):
            print row
$ python csv_dates.py csv_dates.csv
[datetime.date(2011, 7, 27), 'Event 1 Description']
[datetime.date(2011, 7, 28), 'Event 2 Description']
[datetime.date(2011, 7, 29), 'Event 3 Description']





More information about the Python-list mailing list