找到你要的答案

Q:How do I best parse a date string in the Python C API?

Q:我如何最好的解析Python C API的一个日期字符串?

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?

不幸的是,似乎没有pydatetime_fromstring()(相当于如pyfloat_fromstring())在Python的C API。有人想出了什么如果我有解析日期字符串为datetime.datetime型是最理想的方法?

answer1: 回答1:

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.

如果pydatetime_fromtimestamp是不够的,你可以直接调用任何Python方法如strptime:

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

但记住,这pydatetimeapi - >;DateTimeType不是记录的API的一部分,所以它可以打破最终在未来的任何时间。我已经测试了这个版本的python 2.7.9和3.4.2只。相反,你应该在你的C代码做相当于进口日期日期。

python-c-api