Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-122272: guarantee specifiers %F and %C for datetime.strftime to be 0-padded #122436

Merged
Merged
2 changes: 1 addition & 1 deletion Lib/_pydatetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def _can_support_c99():
_supports_c99 = (
_time.strftime("%F", (1900, 1, 1, 0, 0, 0, 0, 1, 0)) == "1900-01-01")
except ValueError:
pass
return False
blhsing marked this conversation as resolved.
Show resolved Hide resolved
return _supports_c99

# Correctly substitute for %z and %Z escapes in strftime formats.
Expand Down
30 changes: 9 additions & 21 deletions Modules/_datetimemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1961,9 +1961,11 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
#endif
) {
/* 0-pad year with century as necessary */
PyObject *item = PyTuple_GET_ITEM(timetuple, 0);
PyObject *item = PyTuple_GetItem(timetuple, 0);
blhsing marked this conversation as resolved.
Show resolved Hide resolved
if (item == NULL) {
goto Done;
}
long year_long = PyLong_AsLong(item);

if (year_long == -1 && PyErr_Occurred()) {
goto Done;
}
Expand All @@ -1989,28 +1991,14 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
goto Done;
}
}
ntoappend = PyOS_snprintf(buf, sizeof(buf),
#ifdef Py_STRFTIME_C99_SUPPORT
if (ch == 'F') {
item = PyTuple_GET_ITEM(timetuple, 1);
long month = PyLong_AsLong(item);
if (month == -1 && PyErr_Occurred()) {
goto Done;
}
item = PyTuple_GET_ITEM(timetuple, 2);
long day = PyLong_AsLong(item);
if (day == -1 && PyErr_Occurred()) {
goto Done;
}
ntoappend = PyOS_snprintf(buf, sizeof(buf), "%04ld-%02ld-%02ld",
year_long, month, day);
}
else {
ch == 'F' ? "%04ld-%%m-%%d" :
#endif
ntoappend = PyOS_snprintf(buf, sizeof(buf), "%04ld", year_long);
"%04ld", year_long);
#ifdef Py_STRFTIME_C99_SUPPORT
if (ch == 'C') {
ntoappend -= 2;
}
if (ch == 'C') {
ntoappend -= 2;
}
#endif
ptoappend = buf;
Expand Down
Loading