summaryrefslogtreecommitdiffstats
path: root/rust/src/python/types/timezone.rs
blob: 1a8bbade08ddf0936581028c6d337f6988d92ab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use pyo3::prelude::*;
use pyo3::types::{PyDelta, PyDict, PyTzInfo};

#[pyclass(module = "_pendulum", extends = PyTzInfo)]
#[derive(Clone)]
pub struct FixedTimezone {
    offset: i32,
    name: Option<String>,
}

#[pymethods]
impl FixedTimezone {
    #[new]
    pub fn new(offset: i32, name: Option<String>) -> Self {
        Self { offset, name }
    }

    fn utcoffset<'p>(&self, py: Python<'p>, _dt: &PyAny) -> PyResult<&'p PyDelta> {
        PyDelta::new(py, 0, self.offset, 0, true)
    }

    fn tzname(&self, _dt: &PyAny) -> String {
        self.__str__()
    }

    fn dst<'p>(&self, py: Python<'p>, _dt: &PyAny) -> PyResult<&'p PyDelta> {
        PyDelta::new(py, 0, 0, 0, true)
    }

    fn __repr__(&self) -> String {
        format!(
            "FixedTimezone({}, name=\"{}\")",
            self.offset,
            self.__str__()
        )
    }

    fn __str__(&self) -> String {
        if let Some(n) = &self.name {
            n.clone()
        } else {
            let sign = if self.offset < 0 { "-" } else { "+" };
            let minutes = self.offset.abs() / 60;
            let (hour, minute) = (minutes / 60, minutes % 60);
            format!("{sign}{hour:.2}:{minute:.2}")
        }
    }

    fn __deepcopy__(&self, py: Python, _memo: &PyDict) -> PyResult<Py<Self>> {
        Py::new(py, self.clone())
    }
}