[C++-sig] boost::posix_time::ptime conversion
Håkon Groven
hgroven at emgs.com
Thu May 15 13:23:24 CEST 2008
Hi again!
Sorry for my late feedback!
I've tried your (Ralf) advise by trying out
http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/faq.html#custom_string
And this works fine!
Actually I'm now converting from ptime to datetime, and from
str(datetime) back to ptime.
Here's some of my code illustrating what I've done:
namespace
{
struct ptime_from_python_datetime_str
{
//str(datetime) => ptime
ptime_from_python_datetime_str()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<boost::posix_time::ptime > ());
}
static void* convertible(PyObject * obj_ptr)
{
if (!PyString_Check(obj_ptr)) return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data * data)
{
const char* value = PyString_AsString(obj_ptr);
if (value == 0) boost::python::throw_error_already_set();
void* storage = (
(boost::python::converter::rvalue_from_python_storage<boost::posix_time::ptime>*)
data)->storage.bytes;
new (storage)
boost::posix_time::ptime(boost::posix_time::time_from_string(value));
data->convertible = storage;
}
};
struct ptime_to_python
{
//ptime => datetime
static PyObject * convert(boost::posix_time::ptime const& pt)
{
boost::gregorian::date date = pt.date();
boost::posix_time::time_duration td = pt.time_of_day();
object result = datetime_datetime(
(int) date.year()
, (int) date.month()
, (int) date.day()
, td.hours()
, td.minutes()
, td.seconds()
);
return incref(result.ptr());
}
};
.
.
.
} //end namespace
BOOST_PYTHON_MODULE(mymodule)
{
.
.
.
ptime_from_python_datetime_str();
to_python_converter<boost::posix_time::ptime, ptime_to_python > ();
.
.
.
}
-Håkon
More information about the Cplusplus-sig
mailing list