Skip to content

Commit 7d5e603

Browse files
add %:z strftime format code
datetime.isoformat generates the tzoffset with colons, but there was no format code to make strftime output the same format. for simplicity and consistency the %:z formatting behaves mostly as %z, with the exception of adding colons. this includes the dynamic behaviour of adding seconds and microseconds only when needed (when not 0). this fixes the still open "generate" part of this issue: #69142
1 parent 32ac98e commit 7d5e603

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

Doc/library/datetime.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2386,6 +2386,12 @@ requires, and these work on all platforms with a standard C implementation.
23862386
| | string if the object is | +063415, | |
23872387
| | naive). | -030712.345216 | |
23882388
+-----------+--------------------------------+------------------------+-------+
2389+
| ``%:z`` | UTC offset in the form | (empty), +00:00, | |
2390+
| | ``±HH:MM[:SS[.ffffff]]`` | -04:00, +10:30, | |
2391+
| | (empty string if the object is | +06:34:15, | |
2392+
| | naive). | -03:07:12.345216 | |
2393+
| | .. versionadded:: 3.12 | | |
2394+
+-----------+--------------------------------+------------------------+-------+
23892395
| ``%Z`` | Time zone name (empty string | (empty), UTC, GMT | \(6) |
23902396
| | if the object is naive). | | |
23912397
+-----------+--------------------------------+------------------------+-------+

Modules/_datetimemodule.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1631,7 +1631,7 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
16311631
ntoappend = 1;
16321632
}
16331633
/* A % has been seen and ch is the character after it. */
1634-
else if (ch == 'z') {
1634+
else if (ch == 'z' || (ch == ':' && *pin == 'z')) {
16351635
if (zreplacement == NULL) {
16361636
/* format utcoffset */
16371637
char buf[100];
@@ -1640,9 +1640,17 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
16401640
if (zreplacement == NULL) goto Done;
16411641
if (tzinfo != Py_None && tzinfo != NULL) {
16421642
assert(tzinfoarg != NULL);
1643+
/* %z -> +HHMM, %:z -> +HH:MM */
1644+
char *sep;
1645+
if (ch == ':') {
1646+
sep = ":";
1647+
pin++;
1648+
} else {
1649+
sep = "";
1650+
}
16431651
if (format_utcoffset(buf,
16441652
sizeof(buf),
1645-
"",
1653+
sep,
16461654
tzinfo,
16471655
tzinfoarg) < 0)
16481656
goto Done;
@@ -1686,7 +1694,7 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
16861694
ntoappend = PyBytes_GET_SIZE(freplacement);
16871695
}
16881696
else {
1689-
/* percent followed by neither z nor Z */
1697+
/* percent followed by something else */
16901698
ptoappend = pin - 2;
16911699
ntoappend = 2;
16921700
}

0 commit comments

Comments
 (0)