diff -r 7f49af7046e4 Doc/library/datetime.rst --- a/Doc/library/datetime.rst Tue Dec 15 11:29:59 2015 +0100 +++ b/Doc/library/datetime.rst Wed Dec 16 22:37:57 2015 +0100 @@ -1133,7 +1133,7 @@ ``self.date().isocalendar()``. -.. method:: datetime.isoformat(sep='T') +.. method:: datetime.isoformat(sep='T', timespec='auto') Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0, @@ -1154,6 +1154,22 @@ >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39' + The optional argument *timespec* specifies the number of additional + terms of the time to include. It can be one of the following: + + - 'auto': Append microseconds except if microsecond is 0. + - 'hours': Append the hour of the day to the date. + - 'minutes': Append the hours and minutes. + - 'seconds': Append the hours, minutes and seconds. + - 'milliseconds': Append the hours, minutes, seconds and milliseconds. + - 'microseconds': Append the hours, minutes, seconds and microseconds. + - 'nanoseconds': Append the hours, minutes, seconds and nanoseconds. + + >>> from datetime import datetime + ... + >>> datetime.datetime.now().isoformat(timespec='minutes') + '2002-12-25T00:00' + .. method:: datetime.__str__() diff -r 7f49af7046e4 Lib/datetime.py --- a/Lib/datetime.py Tue Dec 15 11:29:59 2015 +0100 +++ b/Lib/datetime.py Wed Dec 16 22:37:57 2015 +0100 @@ -152,13 +152,19 @@ dnum = _days_before_month(y, m) + d return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) -def _format_time(hh, mm, ss, us): + +def _format_time(hh, mm=None, ss=None, us=None): # Skip trailing microseconds when us==0. - result = "%02d:%02d:%02d" % (hh, mm, ss) - if us: + result = "%02d" % hh + if mm is not None: + result += ":%02d" % mm + if ss is not None: + result += ":%02d" % ss + if us is not None: result += ".%06d" % us return result + # Correctly substitute for %z and %Z escapes in strftime formats. def _wrap_strftime(object, format, timetuple): # Don't call utcoffset() or tzname() unless actually needed. @@ -1549,7 +1555,7 @@ self._hour, self._minute, self._second, self._year) - def isoformat(self, sep='T'): + def isoformat(self, sep='T', timespec='auto'): """Return the time formatted according to ISO. This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if @@ -1560,10 +1566,40 @@ Optional argument sep specifies the separator between date and time, default 'T'. + + The optional argument timespec specifies the number of additional + terms of the time to include. It can be one of the following: + + 'auto': Append microseconds except if microsecond is 0. + 'hours': Append the hour of the day to the date. + 'minutes': Append the hours and minutes. + 'seconds': Append the hours, minutes and seconds. + 'milliseconds': Append the hours, minutes, seconds and milliseconds. + 'microseconds': Append the hours, minutes, seconds and microseconds. + 'nanoseconds': Append the hours, minutes, seconds and nanoseconds. """ - s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) + - _format_time(self._hour, self._minute, self._second, - self._microsecond)) + if timespec not in ('auto', 'hours', 'minutes', 'seconds', + 'milliseconds', 'microseconds', 'nanoseconds'): + raise ValueError("Unknown timespec value") + + s = '%04d-%02d-%02d%c' % (self._year, self._month, self._day, sep) + + if timespec == 'hours': + s += _format_time(self.hour) + elif timespec == 'minutes': + s += _format_time(self.hour, self.minute) + elif timespec == 'seconds': + s += _format_time(self.hour, self.minute, self.second) + elif timespec == 'milliseconds': + milliseconds = self.microsecond // 1000 + s += _format_time(self.hour, self.minute, self.second, milliseconds) + elif timespec == 'nanoseconds': + nanoseconds = self.microsecond * 1000 + s += _format_time(self.hour, self.minute, self.second, nanoseconds) + else: + s += _format_time(self._hour, self._minute, self._second, + self._microsecond) + off = self.utcoffset() if off is not None: if off.days < 0: diff -r 7f49af7046e4 Lib/test/datetimetester.py --- a/Lib/test/datetimetester.py Tue Dec 15 11:29:59 2015 +0100 +++ b/Lib/test/datetimetester.py Wed Dec 16 22:37:57 2015 +0100 @@ -1556,13 +1556,25 @@ self.assertEqual(dt, dt2) def test_isoformat(self): - t = self.theclass(2, 3, 2, 4, 5, 1, 123) - self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123") - self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123") - self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123") - self.assertEqual(t.isoformat('\x00'), "0002-03-02\x0004:05:01.000123") + t = self.theclass(1, 2, 3, 4, 5, 1, 123) + self.assertEqual(t.isoformat(), "0001-02-03T04:05:01.000123") + self.assertEqual(t.isoformat('T'), "0001-02-03T04:05:01.000123") + self.assertEqual(t.isoformat(' '), "0001-02-03 04:05:01.000123") + self.assertEqual(t.isoformat('\x00'), "0001-02-03\x0004:05:01.000123") + self.assertEqual(t.isoformat(timespec='hours'), "0001-02-03T04") + self.assertEqual(t.isoformat(timespec='minutes'), "0001-02-03T04:05") + self.assertEqual(t.isoformat(timespec='seconds'), "0001-02-03T04:05:01") + self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.000") + self.assertEqual(t.isoformat(timespec='microseconds'), "0001-02-03T04:05:01.000123") + self.assertEqual(t.isoformat(timespec='nanoseconds'), "0001-02-03T04:05:01.000123000") + self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01.000123") + self.assertEqual(t.isoformat(sep=' ', timespec='minutes'), "0001-02-03 04:05") + self.assertRaises(ValueError, t.isoformat, timespec='monkey') # str is ISO format with the separator forced to a blank. - self.assertEqual(str(t), "0002-03-02 04:05:01.000123") + self.assertEqual(str(t), "0001-02-03 04:05:01.000123") + + t = self.theclass(1, 2, 3, 4, 5, 1) + self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01") t = self.theclass(2, 3, 2) self.assertEqual(t.isoformat(), "0002-03-02T00:00:00") diff -r 7f49af7046e4 Modules/_datetimemodule.c --- a/Modules/_datetimemodule.c Tue Dec 15 11:29:59 2015 +0100 +++ b/Modules/_datetimemodule.c Wed Dec 16 22:37:57 2015 +0100 @@ -4488,25 +4488,80 @@ datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { int sep = 'T'; - static char *keywords[] = {"sep", NULL}; + char *timespec = "auto"; + static char *keywords[] = {"sep", "timespec", NULL}; char buffer[100]; - PyObject *result; + PyObject *result = NULL; int us = DATE_GET_MICROSECOND(self); - if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) + if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, ×pec)) return NULL; - if (us) - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + if (strcmp(timespec, "hours") == 0) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d", GET_YEAR(self), GET_MONTH(self), GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), us); - else + DATE_GET_HOUR(self)); + else if (strcmp(timespec, "minutes") == 0) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); + else if (strcmp(timespec, "seconds") == 0) result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", GET_YEAR(self), GET_MONTH(self), GET_DAY(self), (int)sep, DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self)); + else if (strcmp(timespec, "milliseconds") == 0) { + if (us) { + int milliseconds = us / 1000; + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%03d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), milliseconds); + } + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), 0); + } + else if (strcmp(timespec, "nanoseconds") == 0) { + if (us) { + int nanoseconds = us * 1000; + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%09d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), nanoseconds); + } + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), 0); + } + else if (strcmp(timespec, "microseconds") == 0 || (strcmp(timespec, "auto") == 0)) { + if (us) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), us); + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + } + else { + PyErr_Format(PyExc_ValueError, "Unknown timespec value"); + return NULL; + } if (!result || !HASTZINFO(self)) return result;