ulrich
ulrich

Reputation: 3587

convert string into Quantlib Date()

I am reading some parameters data from a csv and I am struggling to convert the date so that it is accepted by the class Date()

I have tried that:

d = datetime.date(datetime.strptime('2011-03-07','%Y-%m-%d'))
Date(d)

but it returns:

NotImplementedError: Wrong number or type of arguments for overloaded function 'new_Date'.

Upvotes: 1

Views: 3767

Answers (4)

Luigi Ballabio
Luigi Ballabio

Reputation: 4343

QuantLib provides a DateParser class that does the job without passing through datetime; you can write

d = DateParser.parseFormatted('2011-03-07','%Y-%m-%d')

to get your Date instance. This also works in C++, where you would write

Date d = DateParser::parseFormatted('2011-03-07','%Y-%m-%d')

or in other languages towards which QuantLib is exported through SWIG.

Upvotes: 8

merlin2011
merlin2011

Reputation: 75589

The quantlib documentation suggests that you should be passing in the following arguments, rather than a Python datetime.

Date (Day d, Month m, Year y)

There does not appear to be Python API documentation at the moment, but according to this answer, it matches the C++, then it should work to simply pass in integers for each value. That is, you would pass in the following arguments for March 3, 2011.

Date(3, 3, 2011)

To convert from the string, you could either manually parse the string, or use the datetime class as you have done.

d = datetime.strptime('2011-03-07','%Y-%m-%d')
quantDate = Date(d.day, d.month, d.year)

Upvotes: 3

Your code is incorrect.

Change this line: d = datetime.date(datetime.strptime('2011-03-07','%Y-%m-%d'))

to this: datetime.datetime.strptime(date_text, '%Y-%m-%d')

It's a minor change but should help.

Upvotes: 0

James
James

Reputation: 36746

Look into using the dateutil module.

from dateutil import parser

parser.parse('2011-03-07')
# datetime.datetime(2011, 3, 7, 0, 0)

Upvotes: 2

Related Questions