2

Unfortunately there seems to be no PyDateTime_FromString() (equivalent to e.g. PyFloat_FromString()) in the Python C API. Has anybody figured out what would be the ideal workaround if I have to parse a date string into a datetime.datetime type?

Thomas F.
  • 381
  • 2
  • 8

1 Answers1

2

If PyDateTime_FromTimestamp does not suffice, you can just call any Python method like strptime directly:

PyObject *datetimeType = (PyObject *) PyDateTimeAPI->DateTimeType;
PyObject *datetime = PyObject_CallMethod(datetimeType, "strptime", "ss",
                                            "11-11-11 11:11:11", //date_string
                                            "%y-%m-%d %H:%M:%S"); //format

But keep in mind, that PyDateTimeAPI->DateTimeType is not part of the documented API, so it could break eventually any time in the future. I've tested this with Python versions 2.7.9 and 3.4.2 only. Instead you should do the equivalent of from datetime import datetime in your C code.

tynn
  • 38,113
  • 8
  • 108
  • 143