如何最好地解析 Python C API 中的日期字符串?
How do I best parse a date string in the Python C API?
不幸的是,Python C API 中似乎没有 PyDateTime_FromString()
(相当于 PyFloat_FromString()
)。如果我必须将日期字符串解析为 datetime.datetime
类型,有没有人想出什么是理想的解决方法?
如果PyDateTime_FromTimestamp
does not suffice, you can just call any Python method like 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 代码中执行相当于 from datetime import datetime
的操作。
不幸的是,Python C API 中似乎没有 PyDateTime_FromString()
(相当于 PyFloat_FromString()
)。如果我必须将日期字符串解析为 datetime.datetime
类型,有没有人想出什么是理想的解决方法?
如果PyDateTime_FromTimestamp
does not suffice, you can just call any Python method like 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 代码中执行相当于 from datetime import datetime
的操作。