why not datetime.strptime() ?

Joshua Spoerri josh at yucs.org
Mon Jan 10 21:11:52 EST 2005


Skip Montanaro <skip <at> pobox.com> writes:
> josh> Shouldn't datetime have strptime?
> If someone wants to get their feet wet with extension module
> programming
> this might be a good place to start.  Mostly, I think nobody who has
> needed/wanted it so far has the round tuits available to spend on the
> task.

OK, it was pretty straightforward. Thanks for the direction.

To whom should I send the patch (attached)?
-------------- next part --------------
--- Modules/datetimemodule.c.orig	2003-10-20 10:34:46.000000000 -0400
+++ Modules/datetimemodule.c	2005-01-10 20:58:38.884823296 -0500
@@ -3774,6 +3774,32 @@
 	return result;
 }
 
+/* Return new datetime from time.strptime(). */
+static PyObject *
+datetime_strptime(PyObject *cls, PyObject *args)
+{
+	PyObject *result = NULL, *obj, *module;
+	const char *string, *format;
+
+	if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
+		return NULL;
+	if ((module = PyImport_ImportModule("time")) == NULL)
+		return NULL;
+	obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
+	Py_DECREF(module);
+
+	result = PyObject_CallFunction(cls, "iiiiiii",
+		PyInt_AsLong(PySequence_GetItem(obj, 0)),
+		PyInt_AsLong(PySequence_GetItem(obj, 1)),
+		PyInt_AsLong(PySequence_GetItem(obj, 2)),
+		PyInt_AsLong(PySequence_GetItem(obj, 3)),
+		PyInt_AsLong(PySequence_GetItem(obj, 4)),
+		PyInt_AsLong(PySequence_GetItem(obj, 5)),
+		PyInt_AsLong(PySequence_GetItem(obj, 6)));
+	Py_DECREF(obj);
+	return result;
+}
+
 /* Return new datetime from date/datetime and time arguments. */
 static PyObject *
 datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
@@ -4385,6 +4411,11 @@
 	 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
 	 	   "(like time.time()).")},
 
+	{"strptime", (PyCFunction)datetime_strptime,
+	 METH_VARARGS | METH_CLASS,
+	 PyDoc_STR("strptime -> new datetime parsed from a string"
+	 	   "(like time.strptime()).")},
+
 	{"combine", (PyCFunction)datetime_combine,
 	 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
 	 PyDoc_STR("date, time -> datetime with same date and time fields")},


More information about the Python-list mailing list