diff options
author | Eric Smith <eric@trueblade.com> | 2007-09-11 18:06:02 (GMT) |
---|---|---|
committer | Eric Smith <eric@trueblade.com> | 2007-09-11 18:06:02 (GMT) |
commit | 1ba3114fdb5adb5e6852c85e1d3caccba3395471 (patch) | |
tree | 0341bc0a923b50960ecf14302132eea3b30142a7 /Modules | |
parent | 54d6874e48cc9aa57c141b59868f6a99a87dd1b6 (diff) | |
download | cpython-1ba3114fdb5adb5e6852c85e1d3caccba3395471.zip cpython-1ba3114fdb5adb5e6852c85e1d3caccba3395471.tar.gz cpython-1ba3114fdb5adb5e6852c85e1d3caccba3395471.tar.bz2 |
Added __format__ method to datetime.datetime, datetime.date, and datetime.time.
If format_spec is empty, __format__ calls str(self), else it calls
self.strftime(format_spec).
Diffstat (limited to 'Modules')
-rw-r--r-- | Modules/datetimemodule.c | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/Modules/datetimemodule.c b/Modules/datetimemodule.c index 14990a3..b48385f 100644 --- a/Modules/datetimemodule.c +++ b/Modules/datetimemodule.c @@ -2440,6 +2440,21 @@ date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) return result; } +static PyObject * +date_format(PyDateTime_Date *self, PyObject *args) +{ + PyObject *format; + + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; + + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Unicode((PyObject *)self); + + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); +} + /* ISO methods. */ static PyObject * @@ -2610,6 +2625,9 @@ static PyMethodDef date_methods[] = { {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("format -> strftime() style string.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, PyDoc_STR("Return time tuple, compatible with time.localtime().")}, @@ -3198,6 +3216,21 @@ time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) return result; } +static PyObject * +time_format(PyDateTime_Time *self, PyObject *args) +{ + PyObject *format; + + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; + + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Unicode((PyObject *)self); + + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); +} + /* * Miscellaneous methods. */ @@ -3385,6 +3418,9 @@ static PyMethodDef time_methods[] = { {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("format -> strftime() style string.")}, + {"__format__", (PyCFunction)time_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, + {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, |