Skip to content

Commit 89bcae7

Browse files
authored
fix time (RustPython#6330)
1 parent c826f9d commit 89bcae7

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

crates/vm/src/stdlib/time.rs

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ mod decl {
311311
vm: &VirtualMachine,
312312
) -> PyResult<StructTimeData> {
313313
let instant = secs.naive_or_utc(vm)?;
314-
Ok(StructTimeData::new(vm, instant, 0))
314+
Ok(StructTimeData::new_utc(vm, instant))
315315
}
316316

317317
#[pyfunction]
@@ -322,7 +322,7 @@ mod decl {
322322
let instant = secs.naive_or_local(vm)?;
323323
// TODO: isdst flag must be valid value here
324324
// https://docs.python.org/3/library/time.html#time.localtime
325-
Ok(StructTimeData::new(vm, instant, -1))
325+
Ok(StructTimeData::new_local(vm, instant, -1))
326326
}
327327

328328
#[pyfunction]
@@ -500,12 +500,13 @@ mod decl {
500500
}
501501

502502
impl StructTimeData {
503-
fn new(vm: &VirtualMachine, tm: NaiveDateTime, isdst: i32) -> Self {
504-
let local_time = chrono::Local.from_local_datetime(&tm).unwrap();
505-
let offset_seconds =
506-
local_time.offset().local_minus_utc() + if isdst == 1 { 3600 } else { 0 };
507-
let tz_abbr = local_time.format("%Z").to_string();
508-
503+
fn new_inner(
504+
vm: &VirtualMachine,
505+
tm: NaiveDateTime,
506+
isdst: i32,
507+
gmtoff: i32,
508+
zone: &str,
509+
) -> Self {
509510
Self {
510511
tm_year: vm.ctx.new_int(tm.year()).into(),
511512
tm_mon: vm.ctx.new_int(tm.month()).into(),
@@ -516,11 +517,25 @@ mod decl {
516517
tm_wday: vm.ctx.new_int(tm.weekday().num_days_from_monday()).into(),
517518
tm_yday: vm.ctx.new_int(tm.ordinal()).into(),
518519
tm_isdst: vm.ctx.new_int(isdst).into(),
519-
tm_gmtoff: vm.ctx.new_int(offset_seconds).into(),
520-
tm_zone: vm.ctx.new_str(tz_abbr).into(),
520+
tm_gmtoff: vm.ctx.new_int(gmtoff).into(),
521+
tm_zone: vm.ctx.new_str(zone).into(),
521522
}
522523
}
523524

525+
/// Create struct_time for UTC (gmtime)
526+
fn new_utc(vm: &VirtualMachine, tm: NaiveDateTime) -> Self {
527+
Self::new_inner(vm, tm, 0, 0, "UTC")
528+
}
529+
530+
/// Create struct_time for local timezone (localtime)
531+
fn new_local(vm: &VirtualMachine, tm: NaiveDateTime, isdst: i32) -> Self {
532+
let local_time = chrono::Local.from_local_datetime(&tm).unwrap();
533+
let offset_seconds =
534+
local_time.offset().local_minus_utc() + if isdst == 1 { 3600 } else { 0 };
535+
let tz_abbr = local_time.format("%Z").to_string();
536+
Self::new_inner(vm, tm, isdst, offset_seconds, &tz_abbr)
537+
}
538+
524539
fn to_date_time(&self, vm: &VirtualMachine) -> PyResult<NaiveDateTime> {
525540
let invalid_overflow = || vm.new_overflow_error("mktime argument out of range");
526541
let invalid_value = || vm.new_value_error("invalid struct_time parameter");

0 commit comments

Comments
 (0)