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?
Asked
Active
Viewed 241 times
2

Thomas F.
- 381
- 2
- 8
1 Answers
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
-
Thanks `strptime` worked for me. `PyDateTime_FromTimestamp` does not help me on Windows since it is Unix related. – Thomas F. Jun 22 '15 at 21:05
-
What does "ss" mean (3rd parameter)? – Andrey Belykh Apr 30 '19 at 19:00
-
I states that `strptime` takes two string parameters. – tynn May 01 '19 at 06:14