2

I'm working on a python c-extension and want to create an instance of python datetime object with a unix timestamp.

On the documentation site ( http://docs.python.org/c-api/datetime.html ) I found the function PyDateTime_FromTimestamp() which returns a new reference based on an input parameter.

The description is as follows: Create and return a new datetime.datetime object given an argument tuple suitable for passing to datetime.datetime.fromtimestamp().

I tried out to call the function with a PyFloat_Object but the function always returns NULL (even if I simply put in 0).

Does somebody have an example how I have to call the function or can give a hint what kind of parameter tuple is required to get it work?

Thanks!

firehead
  • 71
  • 7
  • 1
    The documentation says it takes a tuple. Did you try passing one? – Ignacio Vazquez-Abrams Aug 30 '11 at 21:38
  • Thank you very much - the hint solved my problem! I will add an answer to the question with a working example! – firehead Aug 31 '11 at 03:57
  • unrelated: consider creating an aware datetime object (pass timezone too) otherwise you may lose info because local time may be ambiguous e.g., during end-of-DST transitions when the local time is set back (by an hour usually). Or convert the timestamp into datetime object in UTC instead: `utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)` or use `datetime.utcfromtimestamp()` if timestamp is in range. – jfs Oct 21 '14 at 04:57

1 Answers1

4

Thank you Ignacio! Sometimes small hints make the solution - 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);
firehead
  • 71
  • 7
  • Why pre-init with `NULL` and then set? `static double doubleValue = 1314761451; PyObject *floatObj = PyFloat_FromDouble(doubleValue); PyObject *timeTuple = Py_BuildValue("(O)", floatObj); PyObject *dateTime = PyDateTime_FromTimestamp(timeTuple);` would be fine. – glglgl Aug 31 '11 at 05:03
  • Yes you are right - I took it from my code, where I have all data declarations at the beginning of a function. – firehead Sep 02 '11 at 05:18
  • I believe you can also bypass the `floatObj` step with `timeTuple = Py_BuildValue("(d)", doubleValue); //No longer a "tuple" though`. – Noob Saibot Jan 07 '15 at 19:02
  • Hi, I have tried this snippet. But when calling `PyDateTime_FromTimestamp`, the program exited with a Segmentation fault. Do you have any idea? Thanks. :) – Cosmo Apr 29 '19 at 12:30