Skip to main content

nautilus_core/python/
datetime.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Date/time utility wrappers exposed to Python.
17
18use pyo3::prelude::*;
19use pyo3_stub_gen::derive::gen_stub_pyfunction;
20
21use super::to_pyvalue_err;
22use crate::{
23    UnixNanos,
24    datetime::{
25        is_within_last_24_hours, last_weekday_nanos, micros_to_nanos, millis_to_nanos,
26        nanos_to_micros, nanos_to_millis, nanos_to_secs, secs_to_millis, secs_to_nanos,
27        unix_nanos_to_iso8601, unix_nanos_to_iso8601_millis,
28    },
29};
30
31/// Converts seconds to nanoseconds (ns), rounding to the nearest nanosecond.
32///
33/// # Errors
34///
35/// Returns an error if `secs` is non-finite or cannot be represented as `u64` nanoseconds.
36#[pyfunction(name = "secs_to_nanos")]
37#[gen_stub_pyfunction(module = "nautilus_trader.core")]
38pub fn py_secs_to_nanos(secs: f64) -> PyResult<u64> {
39    secs_to_nanos(secs).map_err(to_pyvalue_err)
40}
41
42/// Converts seconds to milliseconds (ms), rounding to the nearest millisecond.
43///
44/// # Errors
45///
46/// Returns an error if `secs` is non-finite or cannot be represented as `u64` milliseconds.
47#[pyfunction(name = "secs_to_millis")]
48#[gen_stub_pyfunction(module = "nautilus_trader.core")]
49pub fn py_secs_to_millis(secs: f64) -> PyResult<u64> {
50    secs_to_millis(secs).map_err(to_pyvalue_err)
51}
52
53/// Converts milliseconds (ms) to nanoseconds (ns), rounding to the nearest nanosecond.
54///
55/// Returns 0 for a negative input.
56///
57/// # Errors
58///
59/// Returns an error if `millis` is non-finite or cannot be represented as `u64` nanoseconds.
60#[pyfunction(name = "millis_to_nanos")]
61#[gen_stub_pyfunction(module = "nautilus_trader.core")]
62pub fn py_millis_to_nanos(millis: f64) -> PyResult<u64> {
63    millis_to_nanos(millis).map_err(to_pyvalue_err)
64}
65
66/// Converts microseconds (μs) to nanoseconds (ns), rounding to the nearest nanosecond.
67///
68/// Returns 0 for a negative input.
69///
70/// # Errors
71///
72/// Returns an error if `micros` is non-finite or cannot be represented as `u64` nanoseconds.
73#[pyfunction(name = "micros_to_nanos")]
74#[gen_stub_pyfunction(module = "nautilus_trader.core")]
75pub fn py_micros_to_nanos(micros: f64) -> PyResult<u64> {
76    micros_to_nanos(micros).map_err(to_pyvalue_err)
77}
78
79/// Converts nanoseconds (ns) to seconds.
80///
81/// Casting u64 to f64 may lose precision for large values,
82/// but is acceptable when computing fractional seconds.
83#[must_use]
84#[pyfunction(name = "nanos_to_secs")]
85#[gen_stub_pyfunction(module = "nautilus_trader.core")]
86pub fn py_nanos_to_secs(nanos: u64) -> f64 {
87    nanos_to_secs(nanos)
88}
89
90/// Converts nanoseconds (ns) to milliseconds (ms).
91#[must_use]
92#[pyfunction(name = "nanos_to_millis")]
93#[gen_stub_pyfunction(module = "nautilus_trader.core")]
94pub const fn py_nanos_to_millis(nanos: u64) -> u64 {
95    nanos_to_millis(nanos)
96}
97
98/// Converts nanoseconds (ns) to microseconds (μs).
99#[must_use]
100#[pyfunction(name = "nanos_to_micros")]
101#[gen_stub_pyfunction(module = "nautilus_trader.core")]
102pub const fn py_nanos_to_micros(nanos: u64) -> u64 {
103    nanos_to_micros(nanos)
104}
105
106/// Converts a UNIX nanoseconds timestamp to an ISO 8601 (RFC 3339) format string.
107///
108/// All `UnixNanos` values are representable by this formatter.
109#[pyfunction(
110    name = "unix_nanos_to_iso8601",
111    signature = (timestamp_ns, nanos_precision=Some(true))
112)]
113#[gen_stub_pyfunction(module = "nautilus_trader.core")]
114pub fn py_unix_nanos_to_iso8601(
115    timestamp_ns: u64,
116    nanos_precision: Option<bool>,
117) -> PyResult<String> {
118    let unix_nanos = UnixNanos::from(timestamp_ns);
119    let formatted = if nanos_precision.unwrap_or(true) {
120        unix_nanos_to_iso8601(unix_nanos)
121    } else {
122        unix_nanos_to_iso8601_millis(unix_nanos)
123    };
124
125    Ok(formatted)
126}
127
128/// Calculates the last weekday (Mon-Fri) from the given `year`, `month`, and `day`.
129///
130/// # Errors
131///
132/// Returns an error if the date is invalid.
133#[pyfunction(name = "last_weekday_nanos")]
134#[gen_stub_pyfunction(module = "nautilus_trader.core")]
135pub fn py_last_weekday_nanos(year: i32, month: u32, day: u32) -> PyResult<u64> {
136    Ok(last_weekday_nanos(year, month, day)
137        .map_err(to_pyvalue_err)?
138        .as_u64())
139}
140
141/// Check whether the given UNIX nanoseconds timestamp is within the last 24 hours.
142///
143/// # Errors
144///
145/// Returns an error if the timestamp is invalid.
146#[pyfunction(name = "is_within_last_24_hours")]
147#[gen_stub_pyfunction(module = "nautilus_trader.core")]
148pub fn py_is_within_last_24_hours(timestamp_ns: u64) -> PyResult<bool> {
149    is_within_last_24_hours(UnixNanos::from(timestamp_ns)).map_err(to_pyvalue_err)
150}
151
152#[cfg(test)]
153mod tests {
154    use jiff::Timestamp;
155    use pyo3::ffi::c_str;
156    use rstest::rstest;
157
158    use super::*;
159
160    #[rstest]
161    #[case(Some(true), 30)]
162    #[case(Some(false), 24)]
163    fn test_py_unix_nanos_to_iso8601_supports_full_range(
164        #[case] nanos_precision: Option<bool>,
165        #[case] expected_len: usize,
166    ) {
167        let result = py_unix_nanos_to_iso8601(u64::MAX, nanos_precision);
168        assert_eq!(result.unwrap().len(), expected_len);
169    }
170
171    #[rstest]
172    fn test_py_unix_nanos_to_iso8601_formats_valid_timestamp() {
173        let output = py_unix_nanos_to_iso8601(0, Some(false)).unwrap();
174        assert_eq!(output, "1970-01-01T00:00:00.000Z");
175    }
176
177    #[rstest]
178    fn test_jiff_timestamp_python_input_accepts_aware_non_utc_datetime() {
179        Python::initialize();
180        Python::attach(|py| {
181            let datetime = py
182                .eval(
183                    c_str!(
184                        "__import__('datetime').datetime(2024, 1, 15, 13, 30, 45, tzinfo=__import__('datetime').timezone(__import__('datetime').timedelta(hours=-5)))"
185                    ),
186                    None,
187                    None,
188                )
189                .unwrap();
190
191            let timestamp = datetime.extract::<Timestamp>().unwrap();
192            assert_eq!(timestamp, "2024-01-15T18:30:45Z".parse().unwrap());
193        });
194    }
195
196    #[rstest]
197    fn test_jiff_timestamp_python_input_accepts_zoneinfo_datetime() {
198        Python::initialize();
199        Python::attach(|py| {
200            let datetime = py
201                .eval(
202                    c_str!(
203                        "__import__('datetime').datetime(2024, 1, 15, 13, 30, 45, tzinfo=__import__('zoneinfo').ZoneInfo('America/New_York'))"
204                    ),
205                    None,
206                    None,
207                )
208                .unwrap();
209
210            let timestamp = datetime.extract::<Timestamp>().unwrap();
211            assert_eq!(timestamp, "2024-01-15T18:30:45Z".parse().unwrap());
212        });
213    }
214
215    #[rstest]
216    fn test_jiff_timestamp_python_input_rejects_naive_datetime() {
217        Python::initialize();
218        Python::attach(|py| {
219            let datetime = py
220                .eval(
221                    c_str!("__import__('datetime').datetime(2024, 1, 15, 13, 30, 45)"),
222                    None,
223                    None,
224                )
225                .unwrap();
226
227            assert!(datetime.extract::<Timestamp>().is_err());
228        });
229    }
230}