Skip to content

Commit 2e27587

Browse files
authored
Merge pull request #4530 from itsankitkp/handle-panic-strftime-new
Return arg in case of invalid param in strftime
2 parents 84c27f3 + e425538 commit 2e27587

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_time.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ def test_sleep(self):
157157
self.assertRaises(ValueError, time.sleep, -1)
158158
time.sleep(1.2)
159159

160-
@unittest.skip("TODO: RUSTPYTHON, thread 'main' panicked at 'a Display implementation returned an error unexpectedly: Error'")
160+
# TODO: RUSTPYTHON
161+
@unittest.expectedFailure
161162
def test_strftime(self):
162163
tt = time.gmtime(self.t)
163164
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',

extra_tests/snippets/stdlib_datetime.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@ def __init__(self, offset, name):
131131
assert_raises(NotImplementedError, ne.utcoffset, dt)
132132
assert_raises(NotImplementedError, ne.dst, dt)
133133

134+
# unsupport format in strptime returns arg itself
135+
# in linux. Todo: add cases for Mac/Windows
136+
if sys.platform.startswith("linux"):
137+
assert_equal(_time.strftime("%?"), "%?")
138+
134139
# XXX: bug #1302
135140
# def test_normal(self):
136141
#fo = FixedOffset(3, "Three")

vm/src/stdlib/time.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,18 @@ mod time {
207207

208208
#[pyfunction]
209209
fn strftime(format: PyStrRef, t: OptionalArg<PyStructTime>, vm: &VirtualMachine) -> PyResult {
210+
use std::fmt::Write;
211+
210212
let instant = t.naive_or_local(vm)?;
211-
let formatted_time = instant.format(format.as_str()).to_string();
213+
let mut formatted_time = String::new();
214+
215+
/*
216+
* chrono doesn't support all formats and it
217+
* raises an error if unsupported format is supplied.
218+
* If error happens, we set result as input arg.
219+
*/
220+
write!(&mut formatted_time, "{}", instant.format(format.as_str()))
221+
.unwrap_or_else(|_| formatted_time = format.to_string());
212222
Ok(vm.ctx.new_str(formatted_time).into())
213223
}
214224

0 commit comments

Comments
 (0)