Usage of PyDateTime_FromTimestamp

MRAB python at mrabarnett.plus.com
Wed Aug 31 12:41:55 EDT 2011


On 31/08/2011 04:39, Andreas wrote:
> Am 30.08.2011 23:49, schrieb MRAB:
>
>> The key phrase is "argument tuple". The arguments passed to a Python
>> call are always a tuple, not PyFloat_Object.
>>
>> You can build a tuple from the PyFloat_Object using:
>>
>>      Py_BuildValue("(O)", float_object)
>>
>> The "(O)" says to build a tuple ("(...)") containing a single object
>> ("O").
>
Some other points:

Py_BuildValue defaults to building a tuple if the format string
contains multiple items, eg "OO" means the same as "(OO)". In your
case, there is only one, so the (...) is required.

The object returned will have a reference count of 1, and any Python
object passed to the function will have its reference count incremented.

> Thank you very much! That solved my problem.
> Here the full working example:
>
> 		static double doubleValue = 1314761451;
> 		PyObject *floatObj = NULL;
> 		PyObject *timeTuple = NULL;
> 		PyObject *dateTime = NULL;
>
> 		floatObj = PyFloat_FromDouble(doubleValue);
> 		timeTuple = Py_BuildValue("(O)", floatObj);
> 		dateTime = PyDateTime_FromTimestamp(timeTuple);
>
PyFloat_FromDouble returns an object with a reference count of 1 and
Py_BuildValue increments that reference count, so you should probably
be decrementing it afterwards, otherwise you'll have a memory leak. The
usual rule is that you create it, use it, then 'decref' it.

Also, you should be doing some error-checking, seeing if Py_BuildValue,
etc, is returning NULL, indicating an error.



More information about the Python-list mailing list