pub struct Dt {
pub attos: i128,
pub scale: Scale,
pub target: Scale,
}Expand description
The library’s central time type. A high-precision instant/duration with attosecond resolution.
Fields:
- pub attos:
i128- total time in attoseconds since the reference epoch (2000-01-01 noon), as a signed integer. Negative values represent times before the epoch. - pub scale:
Scale- the current time scale of the object. - pub target:
Scale- a target time scale used by many output functions such asDt::to_ymdandDt::to_unix.
Notes:
- In theory it supports a range of roughly ±5.39 trillion years but many of the to and from functions cap at i64 seconds, which can mean a range of ±292 billion years in practice.
- Implements
CopyandClone. Optional derives forserdeandtsifyare available behind the corresponding features. - A wide range of math is available for this type, but it’s not calendar aware, for basic
calendar aware math use the [
YmdHms] type.
§Reference epoch and scales
- The librarys epoch for nearly all functionality such as the conversion functions is
2000-01-01 noon. See also:
Scale. - Leap-second handling follows the chosen
Scale(UTC, UtcSpice, UtcHist).
§See also (non-exhaustive list)
§From and to calendar dates
§From and to str and bytes
Some of these require the alloc feature, they’re marked with *
Dt::from_str_parse*Dt::from_str_ccsdsDt::parseDt::from_strDt::to_str*Dt::to_str_with_offset*Dt::to_str_with_tz*Dt::to_str_iso8601*Dt::to_str_binDt::to_str_bin_with_offsetDt::to_str_bin_with_tz
§From and to julian dates
§Conversions, time scales etc.
Dt::targetDt::from_secDt::to_sec64Dt::from_attosDt::convert_internalDt::to_unixDt::to_ntpDt::to_gps_wk_and_tow
§Conversions from and to types from other libraries
Dt::to_hifitime_epochDt::to_jiff_timestampDt::to_chrono_datetime_utcDt::from_hifitime_epochDt::from_jiff_timestampDt::from_chrono_datetime_utc
§Examples
§Parsing a date
use deep_time::{Dt, Scale};
// uses impl FromStr but Dt::parse provides the same functionality
let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
let ymd = x.to_ymd();
assert_eq!(ymd.yr(), 2000);
assert_eq!(ymd.mo(), 1);
assert_eq!(ymd.day(), 1);
assert_eq!(ymd.hr(), 12);
assert_eq!(ymd.min(), 0);
assert_eq!(ymd.sec(), 0);
assert_eq!(ymd.attos(), 0);§Outputting a date to string / bytes
use deep_time::{Dt, Scale};
let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
let s = x
.to_str_with_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York")
.unwrap();
let b = x
.to_str_bin_with_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York")
.unwrap();
assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");
assert_eq!(b.as_str().unwrap(), "Saturday, January 01, 2000 07:00:00 America/New_York");§Creating a unix timestamp in milliseconds
use deep_time::{Dt, Scale};
// this fn converts from UTC and creates a TAI Dt
let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
// dt is internally TAI but has a UTC tag
let unix_ms = dt.to_unix().to_ms();
// unix timestamp in ms for 2000-01-01 noon UTC
assert_eq!(unix_ms, 946728000000);§Converting time scales
Many functions such as
Dt::to_ymd will convert to
TAI from the Dts current scale then to the Dts target
Scale prior to producing an output.
So you don’t necessarily have to convert time scales prior to using
many of the output functions. You just have to change the target
time scale.
§Using the target field
use deep_time::{Dt, Scale};
// Leap seconds were added to the secounds count
// This Dt has attos that are now on the TAI timescale
let dt = Dt::from_ymd(2025, 1, 1, 0, 0, 0, 0, Scale::UTC);
// The internal target is currently UTC so we don't need to do
// anything to output back to UTC and round trip
let bytes = dt.to_str_bin("%d %m %Y %H:%M:%S").unwrap();
assert_eq!(bytes.as_str().unwrap(), "01 01 2025 00:00:00");
// Perhaps we want to make a GPS timestamp out of our Dt
// If we want it to be on the GPS time scale we have to set the
// target prior to calling to_gps()
let gps = dt.target(Scale::GPS).to_gps().to_sec_f();§Converting the internal attos to a new time scale
use deep_time::{Dt, Scale};
// this fn converts from UTC and creates a TAI Dt
let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
// to tdb
let tdb = dt.to(Scale::TDB);
// then to tt, the current scale is TDB
let tt = tdb.to(Scale::TT);
// then back to TAI
let tai = tt.to(Scale::TAI);
// round trip equality
assert_eq!(dt, tai);§Performing some basic calendar aware math
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 2, 29, 0, 0, 0, 0, Scale::UTC).to_ymd();
let x = x.add_yr(1);
assert_eq!(x.day(), 28);§Changing a dates format
use deep_time::{Dt, StrPTimeFmt};
let fmt = Dt::parse_fmt("%Y-%m-%dT%H:%M:%S").unwrap();
let s = fmt.to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false).unwrap();
assert_eq!(s, "01 01 2000 12:00:00", "expected: {}, got: {}", "01 01 2000 12:00:00", s);Fields§
§attos: i128§scale: Scale§target: ScaleImplementations§
Source§impl Dt
impl Dt
Sourcepub fn from_str_parse(s: &str, opts: &Option<ParseCfg>) -> Result<Dt, DtErr>
pub fn from_str_parse(s: &str, opts: &Option<ParseCfg>) -> Result<Dt, DtErr>
Automatically parses datetime str into a Dt by guessing and generating the format. Supports the vast
majority of date formats.
- Requires the
"alloc"feature. - The returned
Dtis internally on the TAI time scale. Theattosfield is ani128attosecond count since TAI 2000-01-01 noon. See [Scale] for more information.
§Parameters
s: The string to parse. Must be non-empty and no longer than 255 bytes. Empty strings or overly long inputs return an error.opts: OptionalParseCfg. PassNoneto use the defaults.
§Configuration Options (via ParseCfg)
| Field | Default | Effect |
|---|---|---|
lang | En | Language, scroll down to see currently supported languages |
order | Smart | How to resolve ambiguous numeric dates like 01/02/03 |
mode | Auto | Special handling for purely numeric inputs |
parse | None | If provided, these exact strftime-style formats are tried first (and exclusively if mode is Explicit) |
relative | true | Enable phrases like “tomorrow”, “next Friday”, “in 3 days” |
ref_time | None | Reference time for relative dates and syslog-style “no-year” dates (uses system time if std feature is enabled) |
to_lower | true | Automatically lowercase the input, set to false only if it’s already lowercase |
§Purely Numeric Inputs
When the input consists only of digits (and optionally a decimal point),
the parser uses a fast, mode-aware path before trying any other strategies.
The exact interpretation depends on the number of digits and the selected mode.
| Digits | Example(s) | Mode | Interpreted as | Notes |
|---|---|---|---|---|
| 1–4 | 2024, 24, 5 | Auto/Legacy | Year (2-digit uses 2000/1900 pivot) | 1- and 3-digit years only work in Scientific |
| 5 | 24123, 60400 | Legacy | Ordinal date (YYDDD) | — |
| 5 | 60400, 60400.75 | Scientific | Modified Julian Date (MJD) | Fractional days supported |
| 5 | 24123, 60400.75 | Auto | Ordinal (non-decimal) or MJD (decimal) | Smart default |
| 6 | 240315, 202403 | Auto | YYYYMM if plausible year, else YYMMDD | Most common compact form |
| 6 | 240315 | Legacy | YYMMDD preferred | — |
| 6 | 202403 | Scientific | YYYYMM preferred | — |
| 7 | 2024123 | Legacy | Ordinal date (YYYYDDD) | — |
| 7 | 2460123, 2460123.5 | Scientific | Julian Day (JD) | Fractional days supported |
| 7 | 2024123 | Auto | Ordinal (integer) or JD (decimal) | Smart default |
| 10–11 | 1735689600 | any | Unix seconds | — |
| 12–15 | 1735689600123 | any | Unix milliseconds | Most common high-precision case |
| 16–18 | 1735689600123456 | any | Unix microseconds | — |
| 19+ | 1735689600123456789 | any | Unix nanoseconds | Full precision |
Tip: Use Mode::UnixTimestamp when you know the input is always a Unix timestamp.
§Ambiguous Numeric Dates
Dates where the components could map to different orders (e.g. 01/02/03,
3-4-5, 15.03.24, 2024.03.15) are resolved via the order field:
-
Order::Smart(default) — Applies the fast heuristic described inOrder::Smart. It strongly prefers modern/tech conventions (Year-first for compact/ISO-like data) while handling the majority of international and US-style dates. -
Order::Year,Order::Day, orOrder::Monthforce a specific interpretation and bypass the heuristic entirely.
This combination of Smart + Auto mode gives the best real-world parsing
success rate for mixed data sources.
§Other Supported Formats
- ISO 8601 and variants:
2024-03-15,2024-03-15T14:30:00Z,2024-03-15T14:30:00+01:00[Europe/Paris] - Named dates (in supported languages):
15 March 2024,15 mars 2024,15. März 2024,15 de marzo de 2024 - Week dates:
2024-W15,2024-W15-3,2024W153(missing weekday defaults to Monday) - Syslog-style (no year):
Mar 5 10:23:45(year inferred fromref_time) - Relative expressions:
tomorrow,next Friday at 09:00,in 3 days,2 weeks ago - 12-hour time:
2:30 PM,14:30:45.123 - Offsets and timezones:
+0100,-05:30,Z, IANA names in brackets
§Examples
use deep_time::{Dt, ParseCfg, Order, Mode, Lang};
// Default smart parsing
let dt = Dt::from_str_parse("2024-03-15 14:30:00", &None).unwrap();
// German named date
let cfg = ParseCfg { lang: Lang::De, ..Default::default() };
let dt = Dt::from_str_parse("15. März 2024 um 14:30", &Some(cfg)).unwrap();
// Force month-first
let cfg = ParseCfg { order: Order::Month, ..Default::default() };
let dt = Dt::from_str_parse("03/15/2024", &Some(cfg)).unwrap();
// Pure numeric compact form
let dt = Dt::from_str_parse("20240315", &None).unwrap(); // March 15, 2024
// Unix timestamp (milliseconds)
let cfg = ParseCfg { mode: Mode::UnixTimestamp, ..Default::default() };
let dt = Dt::from_str_parse("1735689600123", &Some(cfg)).unwrap();
// Explicit formats only (no fallback)
let cfg = ParseCfg {
parse: Some(vec!["%d/%m/%Y".into(), "%Y-%m-%d".into()]),
mode: Mode::Explicit,
..Default::default()
};
let dt = Dt::from_str_parse("15/03/2024", &Some(cfg)).unwrap();
// Relative date
let dt = Dt::from_str_parse("2 days from now", &None).unwrap();§Notes
- The
Smart+Autocombination gives the best real-world success rate for mixed data. - All successfully parsed
Dtvalues are stored with attosecond precision on the internal TAI timescale. - For maximum reproducibility in production code, prefer
ParseCfgwithparse: Some(...)andmode: Explicit. - Timezone handling (IANA names and fixed offsets) is fully supported.
See also: ParseCfg, Order, Mode, [Lang], Dt,
Dt::str_to_attos, Dt::str_to_ms, Dt::str_to_unix_ms.
§Supported Languages:
- En
- De
- Es
- Fr
Sourcepub fn str_to_attos(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
pub fn str_to_attos(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
Same parsing logic as Dt::from_str_parse,
but returns attoseconds since the library epoch: 2000-01-01 12:00:00 UTC
(on the UTC scale).
Returns Some(attos) on success (negative for pre-2000 dates) or None
on any parse error.
Sourcepub fn str_to_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
pub fn str_to_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
Same parsing logic as Dt::from_str_parse,
but returns milliseconds since the library epoch: 2000-01-01 12:00:00 UTC
(on the UTC scale).
Returns Some(millis) on success (negative for pre-2000 dates) or None
on any parse error.
Sourcepub fn str_to_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
pub fn str_to_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
Same parsing logic as Dt::from_str_parse,
but returns nanoseconds since the library epoch: 2000-01-01 12:00:00 UTC
(on the UTC scale).
Returns Some(nanos) on success (negative for pre-2000 dates) or None
on any parse error.
Sourcepub fn str_to_unix_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
pub fn str_to_unix_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
Same parsing logic as Dt::from_str_parse,
but returns milliseconds since the UNIX epoch: (1970-01-01 00:00:00 UTC).
Returns Some(millis) on success (negative for pre-2000 dates) or None
on any parse error.
Sourcepub fn str_to_unix_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
pub fn str_to_unix_ns(s: &str, opts: &Option<ParseCfg>) -> Option<i128>
Same parsing logic as Dt::from_str_parse,
but returns nanoseconds since the UNIX epoch: (1970-01-01 00:00:00 UTC).
Returns Some(nanos) on success (negative for pre-2000 dates) or None
on any parse error.
Source§impl Dt
impl Dt
Source§impl Dt
impl Dt
Sourcepub const WIRE_VERSION: u8 = 1
pub const WIRE_VERSION: u8 = 1
Current wire format version.
Sourcepub fn to_wire_bytes(&self) -> [u8; 19]
pub fn to_wire_bytes(&self) -> [u8; 19]
Serializes this Dt into a fixed 18-byte little-endian buffer using the
attos: i128 + scale: Scale representation.
§Wire Format
- Byte
0: Version (WIRE_VERSION) - Bytes
[1..17]: total attoseconds as little-endiani128 - Byte
17: scale asu8(enum discriminant) - Byte
18: target asu8(enum discriminant)
Sourcepub fn from_wire_bytes(bytes: &[u8]) -> Option<Self>
pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self>
Deserializes a Dt from exactly 18 bytes of wire data.
Returns None if the version byte is unknown, the length is wrong,
or the scale byte is not a valid Scale variant.
§Wire Format
- Byte
0: Version (WIRE_VERSION) - Bytes
[1..17]: total attoseconds as little-endiani128 - Byte
17: scale asu8(enum discriminant) - Byte
18: target asu8(enum discriminant)
§Security
Safe to call with completely untrusted input. Fixed-size format,
no allocation, no unsafe, and no possibility of code execution.
Source§impl Dt
impl Dt
pub const fn to_drift_as_constant(self, rate: Dt, accel: Dt) -> Drift
pub const fn to_drift_as_rate(self, constant: Dt, accel: Dt) -> Drift
pub const fn to_drift_as_accel(self, constant: Dt, rate: Dt) -> Drift
Source§impl Dt
impl Dt
Sourcepub const fn to_sec(&self) -> i128
pub const fn to_sec(&self) -> i128
If this time were turned into i128 seconds and u64 (always
pushing to the positive) fractional attoseconds, this returns the
whole seconds part.
To just get seconds rounded to the nearest second use
Dt::to_sec_rounded
instead.
§Examples
use deep_time::{Dt, Scale};
// negative 1.3 seconds
let dt = Dt::span(-1_300_000_000_000_000_000);
// becomes positive 700ms
let frac = dt.to_sec_ufrac();
assert_eq!(frac, 700_000_000_000_000_000);
// becomes negative 2 seconds
let sec = dt.to_sec();
assert_eq!(sec, -2);
let dt = Dt::span(1_300_000_000_000_000_000);
assert_eq!(dt.to_sec(), 1);
assert_eq!(dt.to_sec_ufrac(), 300_000_000_000_000_000);
// if you just want rounded seconds
// use to_sec_rounded() instead
let dt = Dt::span(-1_300_000_000_000_000_000);
let sec = dt.to_sec_rounded();
assert_eq!(sec, -1);pub const fn to_sec_rounded(&self) -> i128
pub const fn to_sec64_rounded(&self) -> i64
Sourcepub const fn to_sec64(&self) -> i64
pub const fn to_sec64(&self) -> i64
If this time were turned into i64 seconds and u64 (always
pushing to the positive) fractional attoseconds, this returns the
whole seconds part.
To just get seconds rounded to the nearest second use
Dt::to_sec_rounded
instead.
§Examples
use deep_time::{Dt, Scale};
// negative 1.3 seconds
let dt = Dt::span(-1_300_000_000_000_000_000);
// becomes positive 700ms
let frac = dt.to_sec_ufrac();
assert_eq!(frac, 700_000_000_000_000_000);
// becomes negative 2 seconds
let sec = dt.to_sec64();
assert_eq!(sec, -2);
let dt = Dt::span(1_300_000_000_000_000_000);
assert_eq!(dt.to_sec64(), 1);
assert_eq!(dt.to_sec_ufrac(), 300_000_000_000_000_000);
// if you just want rounded seconds
// use to_sec_rounded() instead
let dt = Dt::span(-1_300_000_000_000_000_000);
let sec = dt.to_sec_rounded();
assert_eq!(sec, -1);Sourcepub const fn to_sec_f(&self) -> Real
pub const fn to_sec_f(&self) -> Real
Converts this Dt to a floating-point number of seconds since the reference
epoch of its associated scale.
- The conversion is lossy, as
Realprovides approximately 15.95 decimal digits of precision.
Sourcepub const fn to_sec_frac(&self) -> i64
pub const fn to_sec_frac(&self) -> i64
If this time were turned into seconds, this returns the fractional attoseconds part.
Sourcepub const fn to_sec_ufrac(&self) -> u64
pub const fn to_sec_ufrac(&self) -> u64
If this time were turned into i64 seconds and u64 (always pushing to the positive) fractional attoseconds, this returns the fractional attoseconds part.
- Always returns a value in the range
0 ≤ x < ATTOS_PER_SEC. - For negative
Dts this is not simply the decimal part of the time in seconds.
§Examples
use deep_time::{Dt, Scale};
// negative 1.3 seconds
let dt = Dt::span(-1_300_000_000_000_000_000);
// becomes positive 700ms
let frac = dt.to_sec_ufrac();
assert_eq!(frac, 700_000_000_000_000_000);
// becomes -2 seconds
let sec = dt.to_sec64();
assert_eq!(sec, -2);
let dt = Dt::span(1_300_000_000_000_000_000);
assert_eq!(dt.to_sec64(), 1);
assert_eq!(dt.to_sec_ufrac(), 300_000_000_000_000_000);Sourcepub const fn round_to_sec(&self) -> Dt
pub const fn round_to_sec(&self) -> Dt
Returns a new Dt rounded to the nearest second.
Sourcepub const fn to_diff_raw(&self, other: Dt) -> Dt
pub const fn to_diff_raw(&self, other: Dt) -> Dt
Sourcepub const fn to_diff_raw_f(&self, other: Dt) -> Real
pub const fn to_diff_raw_f(&self, other: Dt) -> Real
Sourcepub const fn from_diff_raw(attos: i128, epoch: Dt) -> Dt
pub const fn from_diff_raw(attos: i128, epoch: Dt) -> Dt
Low level constructor from total attoseconds since a given epoch.
Simply adds the total attoseconds to the epoch. Does not perform any time scale conversions.
§Examples
use deep_time::{Dt, Scale};
// A leap second from the middle of the table (36 leap seconds accumulated)
let original = Dt::from_ymd(2015, 6, 30, 23, 59, 60, 123_456_789_000_000_000, Scale::UTC);
// Round-trip through canonical attoseconds
let canon = original.to_diff_raw(Dt::UNIX_EPOCH).to_attos();
let roundtrip1 = Dt::from_diff_raw(canon, Dt::UNIX_EPOCH);
assert_eq!(original, roundtrip1, "Canonical round-trip failed");Sourcepub const fn add_attos(&self, n: i128) -> Dt
pub const fn add_attos(&self, n: i128) -> Dt
Adds the specified number of attoseconds to this time value.
Sourcepub const fn add_sec(&self, n: i128) -> Dt
pub const fn add_sec(&self, n: i128) -> Dt
Adds the specified number of seconds to this time value using saturating arithmetic.
Sourcepub const fn add_ms(&self, n: i128) -> Dt
pub const fn add_ms(&self, n: i128) -> Dt
Adds the specified number of milliseconds to this time value.
Sourcepub const fn add_us(&self, n: i128) -> Dt
pub const fn add_us(&self, n: i128) -> Dt
Adds the specified number of microseconds to this time value.
Sourcepub const fn add_ns(&self, n: i128) -> Dt
pub const fn add_ns(&self, n: i128) -> Dt
Adds the specified number of nanoseconds to this time value.
Sourcepub const fn add_ps(&self, n: i128) -> Dt
pub const fn add_ps(&self, n: i128) -> Dt
Adds the specified number of picoseconds to this time value.
Sourcepub const fn add_fs(&self, n: i128) -> Dt
pub const fn add_fs(&self, n: i128) -> Dt
Adds the specified number of femtoseconds to this time value.
Sourcepub const fn add_min(&self, n: i64) -> Dt
pub const fn add_min(&self, n: i64) -> Dt
Adds the specified number of minutes to this time value using saturating arithmetic.
Sourcepub const fn add_hr(&self, n: i64) -> Dt
pub const fn add_hr(&self, n: i64) -> Dt
Adds the specified number of hours to this time value using saturating arithmetic.
Sourcepub const fn is_positive(&self) -> bool
pub const fn is_positive(&self) -> bool
Returns true if this time is strictly positive > 0.
Sourcepub const fn mul(self, rhs: i64) -> Dt
pub const fn mul(self, rhs: i64) -> Dt
Multiplies this time by an integer scalar.
Uses 128-bit arithmetic internally.
Sourcepub const fn div(self, rhs: i64) -> Dt
pub const fn div(self, rhs: i64) -> Dt
Divides this Dt by an integer scalar.
Uses truncating division (rounds toward zero), same as normal integer division.
Returns ZERO if rhs == 0.
Sourcepub const fn floor(&self, unit: Dt) -> Dt
pub const fn floor(&self, unit: Dt) -> Dt
Returns the largest multiple of unit that is ≤ self.
If unit is zero, returns self unchanged (exact, full precision).
Sourcepub const fn ceil(&self, unit: Dt) -> Dt
pub const fn ceil(&self, unit: Dt) -> Dt
Returns the smallest multiple of unit that is ≥ self.
If unit is zero, returns self unchanged (exact, full precision).
Sourcepub const fn round(&self, unit: Dt) -> Dt
pub const fn round(&self, unit: Dt) -> Dt
Returns the nearest multiple of unit.
Halfway cases round away from zero (e.g. 2.5 → 3.0, -2.5 → -3.0),
matching the behavior of the old f64::round().
- If
unitis zero, returnsselfunchanged (preserves full precision). - Uses Euclidean division internally for correct behavior on negative values.
- The result is always a multiple of
unit.
Sourcepub const fn abs_div_floor(&self, unit: Dt) -> usize
pub const fn abs_div_floor(&self, unit: Dt) -> usize
Returns floor(|self| / |unit|) as usize, saturating at usize::MAX.
Fully exact integer arithmetic using 128-bit intermediaries. Used by TimeRange::len.
Sourcepub const fn mul_by_f(&self, rhs: Real) -> Dt
pub const fn mul_by_f(&self, rhs: Real) -> Dt
- Integer part of
rhsis multiplied exactly (pure i128 arithmetic). - Fractional part (|frac| < 1) uses the 10¹⁵ scaling.
Sourcepub const fn div_by_f(&self, rhs: Real) -> Dt
pub const fn div_by_f(&self, rhs: Real) -> Dt
Divides by a real number (routes through the high-precision mul_by_f).
Sourcepub const fn sec_to_attos(sec: i128) -> i128
pub const fn sec_to_attos(sec: i128) -> i128
Converts seconds (i64) → total attoseconds (i128)
Sourcepub const fn attos_to_sec_i64(attos: i128) -> i64
pub const fn attos_to_sec_i64(attos: i128) -> i64
Converts total attoseconds → whole seconds as i64
Sourcepub const fn attos_to_sec_f(attos: u128) -> Real
pub const fn attos_to_sec_f(attos: u128) -> Real
Lossy conversion of u128 attoseconds to → float seconds (s).
Sourcepub const fn attos_to_sec(attos: i128) -> i128
pub const fn attos_to_sec(attos: i128) -> i128
Converts i128 attoseconds → seconds (s)
Sourcepub const fn attos_to_ms(attos: i128) -> i128
pub const fn attos_to_ms(attos: i128) -> i128
Converts i128 attoseconds → milliseconds (ms)
Sourcepub const fn attos_to_us(attos: i128) -> i128
pub const fn attos_to_us(attos: i128) -> i128
Converts i128 attoseconds → microseconds (us)
Sourcepub const fn attos_to_ns(attos: i128) -> i128
pub const fn attos_to_ns(attos: i128) -> i128
Converts i128 attoseconds → nanoseconds (ns)
Sourcepub const fn attos_to_ps(attos: i128) -> i128
pub const fn attos_to_ps(attos: i128) -> i128
Converts i128 attoseconds → picoseconds (ps)
Sourcepub const fn attos_to_fs(attos: i128) -> i128
pub const fn attos_to_fs(attos: i128) -> i128
Converts i128 attoseconds → femtoseconds (fs)
Sourcepub const fn div_dt(self, rhs: Dt) -> Real
pub const fn div_dt(self, rhs: Dt) -> Real
Returns the scalar ratio self / rhs expressed in seconds (as Real).
This is the floating-point equivalent of self.to_sec_f() / rhs.to_sec_f().
§Special cases (chosen for safety and usability in time arithmetic)
non-zero / ZEROreturns±Real::INFINITY(sign matchesself)ZERO / non-zeroreturns0.0ZERO / ZEROreturns1.0(the two durations are identical)
These rules avoid NaN entirely while remaining predictable and useful
in simulations, rate calculations, and control code.
Negative durations are handled correctly (e.g. (-5 s) / (2 s) == -2.5).
This method is const fn and can be used in const contexts.
Sourcepub const fn adjusted_advance(&mut self, elapsed: &Dt, spacetime: &Spacetime)
pub const fn adjusted_advance(&mut self, elapsed: &Dt, spacetime: &Spacetime)
Advances this Dt by the given elapsed duration while applying the relativistic proper-time correction
derived from the supplied Spacetime model.
- This method is intended for simulation of remote clocks (e.g., Earth time as observed from a spacecraft).
- For a local hardware proper-time clock, use the plain
addmethods instead.
Sourcepub const fn adjusted_advance_using_drift(
&mut self,
elapsed: &Dt,
drift: &Drift,
)
pub const fn adjusted_advance_using_drift( &mut self, elapsed: &Dt, drift: &Drift, )
Advances this Dt by the given elapsed duration while applying the relativistic proper-time correction
from a pre-computed Drift value.
- This is an optimized variant of
Dt::adjusted_advancefor callers that already hold aDriftinstance. - This method is intended for simulation of remote clocks (e.g., Earth time as observed from a spacecraft).
- For a local hardware proper-time clock, use the plain
addmethods instead.
Source§impl Dt
impl Dt
Sourcepub const ZERO: Self
pub const ZERO: Self
The library’s internal reference epoch: exactly 2000-01-01 12:00:00 TAI.
[Dt::new(0)].
Sourcepub const NTP_EPOCH: Self
pub const NTP_EPOCH: Self
NTP epoch.
- 1900-01-01 00:00:00 UTC.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -3_155_716_800_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const UNIX_EPOCH: Self
pub const UNIX_EPOCH: Self
UNIX epoch.
- 1970-01-01 00:00:00 TAI.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -946_728_000_000_000_000_000_000_000 attoseconds
- Does not take into account historical UTC offsets from the “rubber time” era.
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const TAI_1977_EPOCH: Self
pub const TAI_1977_EPOCH: Self
TT/TCG/TCB/TDB epoch.
- 1977-01-01 00:00:00 TAI.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -725_803_200_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const CXC_EPOCH: Self
pub const CXC_EPOCH: Self
Chandra X-ray Center (CXC) Time epoch.
- 1998-01-01 00:00:00 TT.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -63_115_232_184_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const GPS_EPOCH: Self
pub const GPS_EPOCH: Self
GPS/Galileo Experiment (GALEX) Time epoch.
- 1980-01-06 00:00:00 UTC.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -630_763_181_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const GALILEO_EPOCH: Self
pub const GALILEO_EPOCH: Self
Galileo System Time (GST) epoch.
- 1999-08-22 00:00:00 GST.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - -11_447_981_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
Sourcepub const BDT_EPOCH: Self
pub const BDT_EPOCH: Self
BeiDou Time (BDT) epoch.
- 2006-01-01 00:00:00 UTC.
- Stored here on the TAI timescale as an offset from
Self::ZERO. - 189_345_633_000_000_000_000_000_000 attoseconds
- The library’s epoch for time scales during conversions is 2000-01-01 12:00:00.
pub const SEC_19: Self
pub const SEC_33: Self
pub const SEC_37: Self
pub const ONE_DAY: Self
Sourcepub const fn new(attos: i128, scale: Scale, target: Scale) -> Dt
pub const fn new(attos: i128, scale: Scale, target: Scale) -> Dt
Creates a new Dt from a total number of attoseconds (signed i128).
Sourcepub const fn span(attos: i128) -> Dt
pub const fn span(attos: i128) -> Dt
Creates a new Dt from a total number of attoseconds (signed i128) without
performing any time scale conversions.
This is an easy way to create a duration.
Sourcepub const fn span_f(sec_f: Real) -> Dt
pub const fn span_f(sec_f: Real) -> Dt
Creates a Dt from a floating-point number of seconds without performing
any time scale conversions.
This is an easy way to create a duration.
Sourcepub const fn from_attos(attos: i128, current: Scale) -> Dt
pub const fn from_attos(attos: i128, current: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total attoseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_tai_sec(sec: i128) -> Dt
pub const fn from_tai_sec(sec: i128) -> Dt
Creates a new Dt from a total number of seconds (signed i128) without
performing any time scale conversions.
Sourcepub const fn from_sec(sec: i128, scale: Scale) -> Dt
pub const fn from_sec(sec: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total seconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_ms(ms: i128, scale: Scale) -> Dt
pub const fn from_ms(ms: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total milliseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_us(us: i128, scale: Scale) -> Dt
pub const fn from_us(us: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total microseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_ns(ns: i128, scale: Scale) -> Dt
pub const fn from_ns(ns: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total nanoseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_ps(ps: i128, scale: Scale) -> Dt
pub const fn from_ps(ps: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total picoseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_fs(fs: i128, scale: Scale) -> Dt
pub const fn from_fs(fs: i128, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Requires a total femtoseconds value.
- The value should be from the epoch TAI 2000-01-01 12:00:00.
- The returned object’s
scalefield is set to TAI and itstargetfield is set to the givenscalearg.
Sourcepub const fn from_min(m: i64, scale: Scale) -> Dt
pub const fn from_min(m: i64, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
Convenience wrapper around
Dt::from_sec.
Sourcepub const fn from_hr(h: i64, scale: Scale) -> Dt
pub const fn from_hr(h: i64, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
Convenience wrapper around
Dt::from_sec.
Sourcepub const fn from_hms(
hr: i64,
min: i64,
sec: i64,
ms: i128,
us: i128,
ns: i128,
scale: Scale,
) -> Dt
pub const fn from_hms( hr: i64, min: i64, sec: i64, ms: i128, us: i128, ns: i128, scale: Scale, ) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Params are hours, minutes, seconds, milliseconds, microseconds, and nanoseconds.
- All values are essentially optional (you can use 0 for ones you want to leave out).
- Negative values are handled.
- Uses saturating arithmetic.
Sourcepub const fn from_days(d: i64, scale: Scale) -> Dt
pub const fn from_days(d: i64, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Convenience wrapper around
Dt::from_sec. - Uses
86400seconds per day in the calculation.
Sourcepub const fn from_wk(wk: i64, scale: Scale) -> Dt
pub const fn from_wk(wk: i64, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Convenience wrapper around
Dt::from_sec. - Uses
604800seconds per week in the calculation.
Sourcepub const fn from_yr(yr: i64, scale: Scale) -> Dt
pub const fn from_yr(yr: i64, scale: Scale) -> Dt
Returns a Dt on the TAI time scale, after having been converted to TAI from
the given scale.
- Convenience wrapper around
Dt::from_sec. - Uses
31_557_600in the calculation.
Sourcepub const fn ago(self, scale: Scale) -> Dt
pub const fn ago(self, scale: Scale) -> Dt
Returns a Dt that is this duration ago from the given scale.
Sourcepub const fn from_now(self, scale: Scale) -> Dt
pub const fn from_now(self, scale: Scale) -> Dt
Returns a Dt that is this duration from now in the given scale.
Sourcepub const fn from_sec_f(sec_f: Real, scale: Scale) -> Dt
pub const fn from_sec_f(sec_f: Real, scale: Scale) -> Dt
Creates a Dt from a floating-point number of seconds.
Sourcepub const fn sec_f_to_total_attos(sec_f: Real) -> i128
pub const fn sec_f_to_total_attos(sec_f: Real) -> i128
High-precision conversion from Real seconds to total attoseconds (i128).
Uses IEEE 754 bit extraction + exact integer multiplication by 5^18.
Returns the correctly rounded integer (round-to-nearest, ties away from zero).
Sourcepub const fn from_sec_f_on(sec_f: Real, s: Scale) -> Dt
pub const fn from_sec_f_on(sec_f: Real, s: Scale) -> Dt
Source§impl Dt
impl Dt
Sourcepub const fn to_ntp(&self) -> Dt
pub const fn to_ntp(&self) -> Dt
Returns this Dt but as an ntp timestamp since the epoch 1900-01-01 00:00:00 UTC.
§Notes:
- Assumes this
Dtis from the 2000-01-01 noon epoch.
§Examples
use deep_time::{Dt, Scale};
// 2698012800
let dt = Dt::from_ymd(1985, 7, 1, 0, 0, 0, 0, Scale::TAI);
let ntp = dt.to_ntp();
assert_eq!(
ntp.to_attos(), Dt::sec_to_attos(2698012800_i128),
"ntp sec for 1985 is wrong, got: {}, expected: {}",
ntp.to_attos(), Dt::sec_to_attos(2698012800_i128)
);
let dt2 = Dt::from_ntp(ntp);
assert_eq!(
dt.to_attos(), dt2.to_attos(),
"round trip to Dt got wrong sec, old: {}, new: {}",
dt.to_attos(), dt2.to_attos()
);
let ymd = dt2.to_ymd();
assert_eq!(ymd.yr(), 1985_i64);
assert_eq!(ymd.mo(), 7);
assert_eq!(ymd.day(), 1);
assert_eq!(ymd.hr(), 0);
assert_eq!(ymd.min(), 0);
assert_eq!(ymd.sec(), 0);
assert_eq!(ymd.attos(), 0);Sourcepub const fn to_gps_wk_and_tow(&self) -> (i64, Dt)
pub const fn to_gps_wk_and_tow(&self) -> (i64, Dt)
Returns the GPS week number and the exact Time of Week (TOW) for this instant when expressed in GPS Time.
- GPS Time is continuous (no leap seconds) and starts at the
Dt::GPS_EPOCH(1980-01-06 00:00:00 UTC). - The returned TOW is a
Dton the TAI scale.
This is the inverse of
Dt::from_gps_wk_and_tow.
week: Full GPS week number (can be negative for dates before 1980).tow: Time of Week as aDt. Values ≥ 604800 seconds are automatically carried into the week number.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::TAI);
let g = x.to_gps_wk_and_tow();
let z = Dt::from_gps_wk_and_tow(g.0, g.1);
assert_eq!(x, z);Sourcepub const fn from_gps_wk_and_tow(wk: i64, tow: Dt) -> Dt
pub const fn from_gps_wk_and_tow(wk: i64, tow: Dt) -> Dt
Creates a Dt from a GPS week number and Time of Week (TOW).
This is the inverse of
Dt::to_gps_wk_and_tow.
week: Full GPS week number (can be negative for dates before 1980).tow: Time of Week as aDt. Values ≥ 604800 seconds are automatically carried into the week number.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::TAI);
let g = x.to_gps_wk_and_tow();
let z = Dt::from_gps_wk_and_tow(g.0, g.1);
assert_eq!(x, z);Sourcepub const fn to_gps(&self) -> Dt
pub const fn to_gps(&self) -> Dt
Returns the elapsed time since the GPS epoch as a Dt on the GPS scale.
The GPS epoch is Dt::GPS_EPOCH.
Sourcepub const fn from_gps(elapsed: Dt) -> Dt
pub const fn from_gps(elapsed: Dt) -> Dt
Inverse of Self::to_gps.
Sourcepub const fn to_gps_day_of_wk(&self) -> u8
pub const fn to_gps_day_of_wk(&self) -> u8
Returns the day of the GPS week (0 = Sunday, 1 = Monday, …, 6 = Saturday).
This value is computed directly from the GPS Time of Week and is independent of the Gregorian calendar or civil time.
Sourcepub const fn to_cxcsec(&self) -> Dt
pub const fn to_cxcsec(&self) -> Dt
Returns the elapsed time since the Chandra X-ray Center (CXC) epoch
as a Dt on the TT scale.
The CXC epoch is Dt::CXC_EPOCH.
Sourcepub const fn from_cxcsec(elapsed: Dt) -> Dt
pub const fn from_cxcsec(elapsed: Dt) -> Dt
Inverse of Self::to_cxcsec.
Sourcepub const fn from_cxcsec_f(elapsed_sec: Real) -> Dt
pub const fn from_cxcsec_f(elapsed_sec: Real) -> Dt
Floating-point counterpart of Self::from_cxcsec.
Sourcepub const fn to_galexsec(&self) -> Dt
pub const fn to_galexsec(&self) -> Dt
Returns the elapsed time since the GPS/Galileo Experiment (GALEX) epoch
as a Dt on the TAI scale.
The GALEX epoch is Self::GPS_EPOCH.
Sourcepub const fn from_galexsec(elapsed: Dt) -> Dt
pub const fn from_galexsec(elapsed: Dt) -> Dt
Inverse of Self::to_galexsec.
Sourcepub const fn from_galexsec_f(elapsed_sec: Real) -> Dt
pub const fn from_galexsec_f(elapsed_sec: Real) -> Dt
Floating-point counterpart of Self::from_galexsec.
Source§impl Dt
impl Dt
Sourcepub const fn to_scale_and_diff(&self, epoch: Dt, convert_epoch: bool) -> Dt
pub const fn to_scale_and_diff(&self, epoch: Dt, convert_epoch: bool) -> Dt
Converts this instant to the target scale and returns the signed difference from the given epoch.
This is a low-level const fn used internally by higher-level conversion
methods such as to_ymd.
§Arguments
to— The time scale to convertselfinto before computing the difference.epoch— The reference epoch (e.g.Dt::UNIX_EPOCH) from which the difference is calculated.
§Returns
A Dt representing the signed difference (seconds + attoseconds) between
this instant (after conversion to to) and the provided epoch.
The returned value is a signed offset relative to epoch in the to scale.
While it is most commonly used as a pure duration, it can also be interpreted
as a timestamp when epoch is something like
Dt::UNIX_EPOCH (e.g. for
generating Unix timestamps via .to_ms() or .to_sec()).
§See also
§Examples
use deep_time::{Dt, Scale};
let dt = Dt::from_ymd(2024, 6, 15, 12, 0, 0, 0, Scale::UTC);
let diff = dt.to_scale_and_diff(Dt::UNIX_EPOCH, true);
// diff can be used as a Unix timestamp offset
let unix_ms = diff.to_ms();
assert!(unix_ms > 1_700_000_000_000);Sourcepub const fn from_diff_and_scale(diff: Dt, epoch: Dt, convert_epoch: bool) -> Dt
pub const fn from_diff_and_scale(diff: Dt, epoch: Dt, convert_epoch: bool) -> Dt
Creates a TAI Dt by adding a difference to an epoch and interpreting
the result on the given time scale.
This is the inverse counterpart to
Dt::to_scale_and_diff
and is used by Dt::from_ymd
and related constructors.
§Arguments
diff— The signed difference (as aDt) to add to the epoch.epoch— The reference epoch (commonlyDt::UNIX_EPOCHorDt::ZERO).current— The time scale on whichdiff+epochshould be interpreted.
§Returns
A Dt on the TAI scale representing the absolute instant
epoch + diff when interpreted on current.
§Notes
- The input
diffis treated as being on thecurrentscale. - The final result is always converted to TAI (the internal canonical representation).
§See also
§Examples
use deep_time::{Dt, Scale};
let diff = Dt::from_tai_sec(1_718_467_200); // ~2024-06-15
let dt = Dt::from_diff_and_scale(diff, Dt::UNIX_EPOCH, true);
let ymd = dt.to_ymd();
assert_eq!(ymd.yr(), 2024);
assert_eq!(ymd.mo(), 6);
assert_eq!(ymd.day(), 15);Sourcepub const fn to_tai(&self) -> Dt
pub const fn to_tai(&self) -> Dt
Converts the internal attos to be on the TAI time Scale.
use deep_time::{Dt, Scale};
let tai = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);
let tt = tai.to(Scale::TT);
assert_eq!(tt.scale, Scale::TT);
let roundtrip = tt.to_tai();
assert_eq!(tai.scale, Scale::TAI);
assert_eq!(roundtrip, tai);See Dt::to for more info.
Sourcepub const fn convert(&self, new: Scale) -> Dt
pub const fn convert(&self, new: Scale) -> Dt
Converts directly to new Scale, without first converting to TAI.
Warning:
Sourcepub const fn to(&self, new: Scale) -> Dt
pub const fn to(&self, new: Scale) -> Dt
Converts this instant to another time scale, going via TAI.
Essentially when converting TT to TDB the internal process goes like TT
-> TAI -> TDB. It uses the Dts scale field to determine what scale
to convert from to TAI, and then the new arg dictates the new time scale.
- It is not necessary to do this if you just want to use such functions
as
Dt::to_ymdas these internally convert to the scale of the object’stargetfield before output. - If a TAI
Dtwas created usingDt::from_ymdand the datetime had 60 seconds, converting to UTC would lose that info. To round trip a 60 second UTC datetime you need only set theDt::targetScaletoUTCand then call the desired output function, such asDt::to_ymd. - The internal
attosfield changes to be on the new time scale. - The
Dtstargetfield is ignored and left unchanged. - The
Dtsscalefield is changed to the newScale.
§Returns
- A
Dtrepresenting the same physical instant but on thenewscale. - The returned objects
scalefield has been changed tonew.
If current == new, this method returns *self without any computation.
§See also
§Examples
use deep_time::{Dt, Scale};
let tai = Dt::from_ymd(2024, 6, 15, 12, 0, 0, 0, Scale::UTC);
let tt = tai.to(Scale::TT);
let tdb = tt.to(Scale::TDB);
let roundtrip = tdb.to(Scale::TAI);
let ymd = roundtrip.to_ymd();
assert_eq!(ymd.yr(), 2024);
assert_eq!(ymd.mo(), 6);
assert_eq!(ymd.day(), 15);
assert_eq!(ymd.hr(), 12);
assert_eq!(ymd.min(), 0);
assert_eq!(ymd.sec(), 0);
assert_eq!(ymd.attos(), 0);Sourcepub const fn convert_using_drift(self, reference: Dt, drift: Drift) -> Dt
pub const fn convert_using_drift(self, reference: Dt, drift: Drift) -> Dt
Sourcepub const fn convert_back_using_drift(self, reference: Dt, drift: Drift) -> Dt
pub const fn convert_back_using_drift(self, reference: Dt, drift: Drift) -> Dt
Performs the inverse conversion of Dt::convert_using_drift, recovering the original proper
time on the source clock scale.
A fixed-point iteration (at most 16 steps) is used to solve the implicit equation. For the common case of a pure constant offset the function returns immediately without iteration.
Source§impl Dt
impl Dt
Sourcepub const fn from_jyear(jyear: Real, scale: Scale) -> Dt
pub const fn from_jyear(jyear: Real, scale: Scale) -> Dt
Inverse of Self::to_jyear.
Sourcepub const fn from_byear(byear: Real, scale: Scale) -> Dt
pub const fn from_byear(byear: Real, scale: Scale) -> Dt
Inverse of Self::to_byear.
Sourcepub fn to_decimalyear(&self) -> Real
pub fn to_decimalyear(&self) -> Real
Returns the decimal year (Gregorian calendar year + fraction of the year).
This is the direct equivalent of Astropy’s Time.decimalyear:
- Uses the actual length of the specific Gregorian year (365 or 366 days, plus any leap seconds on UTC/UtcSpice/etc.).
- Fully scale-aware (TAI, TT, UTC, TDB, custom clocks, …).
- Exact integer arithmetic for the year boundaries, then a high-precision
to_sec_fdivision (lossy only at the finalRealstep, same as Astropy).
Source§impl Dt
impl Dt
Sourcepub fn from_str_ccsds(input: &str) -> Result<Self, DtErr>
pub fn from_str_ccsds(input: &str) -> Result<Self, DtErr>
Generalized CCSDS ASCII Time Code parser (A or B variant).
Handles both calendar (%Y-%m-%d) and day-of-year (%Y-%j) formats.
All time components after the date portion are optional.
Sourcepub fn from_ccsds_ccs(input: &[u8]) -> Result<Dt, DtErr>
pub fn from_ccsds_ccs(input: &[u8]) -> Result<Dt, DtErr>
Parses a CCSDS CCS (Calendar Segmented Time Code) binary time code
directly into TimeParts.
Implements CCSDS 301.0-B-4 §3.4 (Level 1 only).
§P-field (exactly 1 byte)
- Bit 7: Extension flag → must be
0(we reject extensions) - Bits 6-4: Code ID =
101 - Bit 3: Calendar type (
0= Month/Day,1= Day-of-Year) - Bits 2-0: Number of subsecond BCD octets (
0–6)
§T-field (BCD, big-endian)
- 2 bytes: Year (0001–9999)
- 2 bytes: Month+Day (01-12,01-31) or Day-of-Year (001–366)
- 3 bytes: Hour (00-23), Minute (00-59), Second (00-60)
- 0–6 bytes: Fractional seconds (exactly 2 decimal digits per byte)
Epoch: 1958-01-01 00:00:00 UTC (identical to CDS).
Sourcepub fn from_ccsds_c(input: &[u8]) -> Result<Dt, DtErr>
pub fn from_ccsds_c(input: &[u8]) -> Result<Dt, DtErr>
Parses a CCSDS C (CUC – Unsegmented Time Code) binary time code
directly into Dt.
This function implements CCSDS 301.0-B-4 §3.2 (Level 1 only) with full support for the extended P-field (second octet) as defined in the standard.
§Supported formats (Level 1 only)
- 1-byte or 2-byte P-field (further extension beyond 2 bytes is rejected).
- Code ID must be
001(1958-01-01 TAI epoch). - Coarse time: 1–7 octets (base 1–4 from Octet 1 + up to 3 additional from Octet 2).
- Fractional time: 0–10 octets (base 0–3 from Octet 1 + up to 7 additional from Octet 2).
§P-field decoding (when Bit 0 of Octet 1 = 1)
- Octet 2:
- Bit 0: Further-extension flag (must be 0; we reject 3+-byte P-fields).
- Bits 1-2: Additional coarse octets (0–3).
- Bits 3-5: Additional fractional octets (0–7).
- Bits 6-7: Reserved for mission definition (ignored).
§Precision
Fractional seconds are converted to attoseconds with exact integer scaling
(value / 2^(8·n_frac)). Larger n_frac gives higher resolution (down to ~2⁻⁸⁰ s
with 10 fractional bytes).
§Returns
A Dt with scale = TAI and tz = Utc.
§Errors
- [
DtErrKind::CCSDSBinEmpty] if the input is empty. - [
DtErrKind::CCSDSBinTooShort] if the input is too short for the declared P-field / T-field sizes or otherwise malformed. - [
DtErrKind::CCSDSBinInvalidCodeId] if the Code ID is not001. - [
DtErrKind::CCSDSBinInvalidPFieldExtension] if the further-extension flag is set (3+ byte P-field, unsupported).
Sourcepub fn from_ccsds_d(input: &[u8]) -> Result<Dt, DtErr>
pub fn from_ccsds_d(input: &[u8]) -> Result<Dt, DtErr>
Parses a CCSDS D (CDS – Day Segmented Time Code) binary time code
directly into Dt.
This function implements CCSDS 301.0-B-4 §3.3 (Level 1 only).
§Supported formats
- 1-byte or 2-byte P-field.
- Code ID must be
100and Epoch bit must be0(1958-01-01 UTC epoch). n_day: 2 or 3 bytes for the day count.- Middle field is always 4 bytes of milliseconds since midnight.
- Sub-millisecond field (bits 6-7 of P-field):
00: no fractional field01: 2 bytes (microseconds of the millisecond, 0–65535)10: 4 bytes (2⁻³² of the millisecond)
§Precision
- The millisecond field is rounded to the nearest millisecond (in the encoder).
- With 2-byte sub-ms: maximum quantization error ≈ ±7.63 ns.
- With 4-byte sub-ms: maximum quantization error ≈ ±0.116 ps.
§Returns
A Dt with timescale = Utc and tz = Utc.
§Errors
- [
DtErrKind::CCSDSBinEmpty] if the input is empty. - [
DtErrKind::CCSDSBinTooShort] if the input is too short for the declared field sizes. - [
DtErrKind::CCSDSBinInvalidCodeId] if the Code ID is not100. - [
DtErrKind::CCSDSBinInvalidEpoch] if the Epoch bit is set (non-Level-1 / non-1958 epoch). - [
DtErrKind::CCSDSBinInvalidSubMillisecondCode] if bits 6-7 encode an unsupported value (0b11).
Sourcepub fn from_ccsds_bin(input: &[u8]) -> Result<Dt, DtErr>
pub fn from_ccsds_bin(input: &[u8]) -> Result<Dt, DtErr>
Auto-detects and parses a CCSDS binary time code (CUC, CDS, or CCS) based on the Code ID in the first P-field byte.
Convenience wrapper around TimeParts::from_ccsds_bin.
§Supported formats
- Code ID
001→ CUC (Unsegmented) - Code ID
100→ CDS (Day Segmented) - Code ID
101→ CCS (Calendar Segmented)
§Errors
- [
DtErrKind::CCSDSBinEmpty] if the input is empty. - [
DtErrKind::CCSDSBinInvalidCodeId] for any other Code ID.
Source§impl Dt
impl Dt
Sourcepub fn parse(s: &str) -> Result<Self, DtErr>
pub fn parse(s: &str) -> Result<Self, DtErr>
Parses a date/time string.
- When the
parsefeature is enabled: uses the smart auto-parser. - When the
parsefeature is disabled: falls back to CCSDS format.
§Examples
use deep_time::{Dt, Scale};
// uses impl FromStr but Dt::parse provides the same functionality
let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
let ymd = x.to_ymd();
assert_eq!(ymd.yr(), 2000);
assert_eq!(ymd.mo(), 1);
assert_eq!(ymd.day(), 1);
assert_eq!(ymd.hr(), 12);
assert_eq!(ymd.min(), 0);
assert_eq!(ymd.sec(), 0);
assert_eq!(ymd.attos(), 0);§See also
Sourcepub fn from_str(
s: &str,
fmt: &str,
inp_can_end_before_fmt: bool,
fmt_can_end_before_inp: bool,
allow_partial_date: bool,
) -> Result<Dt, DtErr>
pub fn from_str( s: &str, fmt: &str, inp_can_end_before_fmt: bool, fmt_can_end_before_inp: bool, allow_partial_date: bool, ) -> Result<Dt, DtErr>
High-level parser equivalent to C strptime (and Python strptime).
Parses the input string s according to the supplied format string fmt
and returns a Dt directly. This is a convenience wrapper around
TimeParts::from_str
followed by TimeParts::to_dt.
It supports the same set of % directives as the low-level parser, pretty
much the same as jiff.
§Parameters
s: The date/time string to parse.fmt: The format string containing%directives (must be valid ASCII).inp_can_end_before_fmt: Iftrue, the input may end before the format string is fully consumed (extra format specifiers are ignored).fmt_can_end_before_inp: Iftrue, the format may end before the input is fully consumed (trailing characters in the input are allowed).allow_partial_date: Iftrue, a missing month/day will be defaulted to1instead of returning an [Incomplete] error.
§Errors
Returns DtErr for:
- Parse failures (
InvalidFormat,OutOfRange,UnknownDirective, etc.) - Incomplete data when
allow_partial_dateisfalse - Trailing characters (when
fmt_can_end_before_inpisfalse)
See TimeParts::from_str for the complete list of supported directives
and detailed parsing semantics.
Sourcepub fn parse_fmt(strptime_fmt: &str) -> Result<StrPTimeFmt, DtErr>
pub fn parse_fmt(strptime_fmt: &str) -> Result<StrPTimeFmt, DtErr>
Parses and validates a strptime-style format string into a reusable StrPTimeFmt.
The format is checked once for syntax errors and unsupported directives,
then stored in a compact fixed-size buffer. The resulting StrPTimeFmt is
Copy, cheap to clone, and can be used repeatedly with StrPTimeFmt::to_dt
and StrPTimeFmt::to_str without re-validating.
Only ASCII formats up to 256 bytes are accepted.
§Parameters
strptime_fmt: The format string using%directives (e.g."%Y-%m-%d %H:%M:%S","%F %T","%Y-%m-%dT%H:%M:%S%.3fZ").
§Errors
Returns DtErr if the format is:
- Longer than 256 bytes
- Not valid ASCII
- Contains unknown, unsupported, or malformed directives
Sourcepub fn from_iso_duration(s: &str) -> Result<Dt, DtErr>
pub fn from_iso_duration(s: &str) -> Result<Dt, DtErr>
Parses an ISO 8601 duration string into a Dt representing a pure time interval.
Supports the full PnYnMnDTnHnMnS format (case-insensitive), including:
- Optional leading
+or-sign P/pprefix (required)- Optional
T/tseparator between date and time parts - Weeks (
W/w) - Fractional seconds with up to 18 digits of precision (attosecond resolution)
The returned Dt is a duration (signed interval) on the TAI scale.
It can be added to/subtracted from other Dt values, multiplied/divided,
rounded, etc.
§Not Reference-Time Aware
This parser is not reference-time aware. Calendar units (Y, M) are
converted to a fixed number of seconds using standard average lengths
rather than being resolved against a specific date. This makes parsing
fast and allocation-free, but P1M always represents exactly the same
duration regardless of context.
§Parameters
s: The ISO 8601 duration string (e.g."P1Y2M3DT4H5M6.123456789012345678S","-PT30M","P7W","+P1DT12H").
§Errors
Returns DtErr for:
- Empty string
- Missing
Pprefix - Invalid syntax (
Twith no time part, multipleTs, etc.) - Unknown unit designators
- Numeric values that are out of range or cause overflow
Sourcepub fn looks_like_iso(s: &str) -> bool
pub fn looks_like_iso(s: &str) -> bool
Accepts: P1Y, -P2W, PT1.5H, P1DT2H30M, +P3D, p1y, P1,5S, PT0S, etc.
Rejects: anything with whitespace, lone “P”/“-P”/“PT”, “P123”, “Please wait 5m”,
“1.5h”, “P1Yabc”, “P1Y!”, or any string longer than 128 bytes.
Source§impl Dt
impl Dt
Sourcepub const fn unix_sec_to_ymd(unix_sec: i64) -> (i64, u8, u8)
pub const fn unix_sec_to_ymd(unix_sec: i64) -> (i64, u8, u8)
Converts a Unix timestamp (seconds since 1970-01-01 00:00:00) to a proleptic Gregorian date (year, month, day).
Sourcepub fn to_ymd_rich(&self) -> YmdHmsRich
pub fn to_ymd_rich(&self) -> YmdHmsRich
Returns the full proleptic Gregorian date and wall-clock time for this instant, including all precomputed calendar metadata (ISO week date, day-of-year, multiple week-numbering systems, etc.).
This is the “heavy” version of to_ymd.
It performs the same scale conversion but additionally computes and stores every common calendar-derived field. This means downstream formatting code does not have to re-calculate these numbers for the same object.
The returned YmdHmsRich has convenient and fast formatter methods for turning
the object into a datetime - an array of u8 or String
(requires "alloc" feature).
§See also
Dt::to_ymd— the lightweight version.YmdHmsRich— the rich struct type and its accessor methods.YmdHmsRich::to_str— basically like strftime.
§What you get in YmdHmsRich
In addition to the fields returned by to_ymd,
the returned struct also contains:
iso_yr,iso_wk,iso_wkday— ISO 8601 week date (Monday-based week)day_of_yr— ordinal day of the year (1-based)wkday— weekday number (0 = Sunday … 6 = Saturday)wk_of_yr_sun— Sunday-based week number (%Uin strftime, range0..=53)wk_of_yr_mon— Monday-based week number (%Win strftime, range0..=53)scale— the time scale used for the conversion (new)
All other fields (unix_attosec, yr…attos, offset_sec, tz, tz_abbrev)
are populated exactly as in the lightweight YmdHms version.
§Performance note
This function performs several extra calendar calculations (ISO week date,
day-of-year, both week-numbering systems). If you only need the basic YMDHMS
components, prefer to_ymd for speed.
§Examples
use deep_time::{Dt, Scale};
let dt = Dt::from_ymd(2024, 6, 15, 12, 30, 45, 0, Scale::UTC);
let rich = dt.to_ymd_rich();
assert_eq!(rich.yr(), 2024);
assert_eq!(rich.iso_wk(), 24); // ISO week 24
assert_eq!(rich.day_of_yr(), 167); // June 15 is day 167
assert_eq!(rich.wkday_sun(), 6); // SaturdaySourcepub fn to_ymd(&self) -> YmdHms
pub fn to_ymd(&self) -> YmdHms
Returns the proleptic Gregorian date and wall-clock time for this instant.
Converts to this Dts target time scale using the internal current
scale before producing a result.
§Returns
A YmdHms containing:
yr,mo,day— proleptic Gregorian calendar datehr(0–23),min(0–59),sec(0–60)attos— fractional second in attoseconds (0 ≤ attos < 10¹⁸)unix_attosec— total attoseconds since the Unix epoch (1970-01-01 00:00:00 UTC) when this instant is expressed in thenewscale
§Leap-second handling
If new is one of the scales that use leap seconds (UTC, UtcSpice, or UtcHist)
and the instant falls exactly on a leap second, the returned sec will be 60.
In every other case sec is in the range 0..=59.
The implementation converts internally to TAI before checking leap-second status, ensuring correct detection regardless of the input scale.
§See also
§Examples
use deep_time::{Dt, Scale};
// `from_ymd` always returns a TAI instant
let dt = Dt::from_ymd(2024, 6, 15, 12, 30, 45, 0, Scale::UTC);
let ymd = dt.to_ymd();
assert_eq!(ymd.yr(), 2024);
assert_eq!(ymd.mo(), 6);
assert_eq!(ymd.day(), 15);
assert_eq!(ymd.hr(), 12);
assert_eq!(ymd.min(), 30);
assert_eq!(ymd.sec(), 45);
assert!(ymd.attos() == 0);Sourcepub const fn ymd_to_unix_sec(
yr: i64,
mo: u8,
day: u8,
hr: u8,
min: u8,
sec: u8,
) -> i64
pub const fn ymd_to_unix_sec( yr: i64, mo: u8, day: u8, hr: u8, min: u8, sec: u8, ) -> i64
Converts a proleptic Gregorian calendar date+time to a Unix timestamp (seconds since 1970-01-01 00:00:00).
- Expects 1 based
moandday, and 0 basedhr,min, andsec. - Does not perform any time scale conversions.
- Expects clamped values.
Sourcepub const fn jd_to_ymd(jd: i64) -> (i64, u8, u8)
pub const fn jd_to_ymd(jd: i64) -> (i64, u8, u8)
Converts a Julian Day Number (JD) to a proleptic Gregorian calendar date.
- Returns
(year, month, day)wheremonth∈ [1, 12] andday∈ [1, 31] (standard 1-based Gregorian values). - This is the inverse of
Dt::ymd_to_jd. - Supports the full
i64range, including negative years and year zero.
Sourcepub const fn ymd_to_jd(yr: i64, mo: u8, day: u8) -> i64
pub const fn ymd_to_jd(yr: i64, mo: u8, day: u8) -> i64
Computes the Julian Day Number (JD) for a proleptic Gregorian calendar date at noon UT.
This is the inverse of [jd_to_ymd].
§Arguments
yr- Year (anyi64; proleptic Gregorian)mo- Month (1-based:1= January,2= February, …,12= December)day- Day of the month (1-based:1= first day of the month)
The algorithm matches the standard astronomical convention used throughout the library
(ymd_to_jd(2000, 1, 1) == 2451545).
§Notes
- This function expects 1 based
moandday. Passingmo = 0orday = 0(or other out-of-range values) will produce incorrect results as this function does not perform value clamping. - Does not deal with bad inputs like February with 30 days, does not do any clamping. If you
need to sanitize a year, month, day input use
Dt::clamp_mdhmsfirst. - The result is the integer JD corresponding to noon on the given date.
Sourcepub const fn from_ymd(
yr: i64,
mo: u8,
day: u8,
hr: u8,
min: u8,
sec: u8,
attos: u64,
scale: Scale,
) -> Dt
pub const fn from_ymd( yr: i64, mo: u8, day: u8, hr: u8, min: u8, sec: u8, attos: u64, scale: Scale, ) -> Dt
Creates a TAI Dt from a proleptic gregorian date which is assumed to be on
the provided time scale.
- Equivalent to
Dt::fromfor the provided date. Except that conversion is performed prior to adding an extra second if the givensecis60. - Returned
Dtwill be on the TAI time scale.
All input components are clamped to their valid ranges:
mo→ 1..=12 1 basedday→ 1..=31 1 basedhr→ 0..=23 0 basedmin→ 0..=59 0 basedsec→ 0..=60 0 based (permits leap seconds)attos→ 10¹⁸ 0 based (clamped to under 1 second)
Sourcepub const fn ydoy_to_jd(yr: i64, day_of_yr: u16) -> i64
pub const fn ydoy_to_jd(yr: i64, day_of_yr: u16) -> i64
Computes the Julian Day Number from a Gregorian year and ordinal day-of-year.
Sourcepub const fn jd_to_wkday(jd: i64) -> u8
pub const fn jd_to_wkday(jd: i64) -> u8
Converts a Julian Day Number to the corresponding weekday number (0 = Sunday … 6 = Saturday).
Sourcepub const fn iso_wk_to_jd(iso_yr: i64, iso_wk: u8, wkday: Weekday) -> i64
pub const fn iso_wk_to_jd(iso_yr: i64, iso_wk: u8, wkday: Weekday) -> i64
Computes the Julian Day Number from an ISO week date (Monday-based week).
Sourcepub const fn wk_sun_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64
pub const fn wk_sun_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64
Computes the Julian Day Number from a Sunday-based week-of-year (%U).
Sourcepub const fn wk_mon_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64
pub const fn wk_mon_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64
Computes the Julian Day Number from a Monday-based week-of-year (%W).
Sourcepub const fn is_leap_yr(yr: i64) -> bool
pub const fn is_leap_yr(yr: i64) -> bool
Returns true if the given year is a Gregorian leap year under proleptic rules.
Sourcepub const fn is_valid_ymd(yr: i64, mo: u8, day: u8) -> bool
pub const fn is_valid_ymd(yr: i64, mo: u8, day: u8) -> bool
Returns true if the supplied values form a valid proleptic Gregorian calendar date.
Sourcepub const fn has_iso_wk_53(yr: i64) -> bool
pub const fn has_iso_wk_53(yr: i64) -> bool
Returns true if the given Gregorian year contains an ISO week 53.
Sourcepub fn day_of_yr(&self, ymd: Option<(i64, u8, u8)>) -> u16
pub fn day_of_yr(&self, ymd: Option<(i64, u8, u8)>) -> u16
Returns the ordinal day of the year (1-based).
January 1 is day 1; December 31 is day 365 or 366 (in leap years).
Uses the proleptic Gregorian calendar.
Sourcepub fn wk_sun(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8
pub fn wk_sun(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8
Sunday-based week number (%U in strftime).
Range: 0..=53.
- Week 0 contains the days before the first Sunday of the year.
- Week 1 begins on the first Sunday of the year.
The optional ymd and doy arguments are performance optimisations
(same pattern used throughout the file for day_of_year, to_iso_wk_date, etc.).
Pass whichever you already have; the function will use the fastest path.
Sourcepub fn wk_mon(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8
pub fn wk_mon(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8
Monday-based week number (%W in strftime).
Range: 0..=53.
- Week 0 contains the days before the first Monday of the year.
- Week 1 begins on the first Monday of the year.
The optional ymd and doy arguments are performance optimisations
(same pattern as wk_sun, day_of_yr, to_iso_wk_date, etc.).
Sourcepub fn to_iso_wk_date(&self, ymd: Option<(i64, u8, u8)>) -> (i64, u8, Weekday)
pub fn to_iso_wk_date(&self, ymd: Option<(i64, u8, u8)>) -> (i64, u8, Weekday)
Returns the ISO 8601 week date for this Dt.
Returns (iso_year, iso_week, weekday) where:
iso_yearis the ISO week year (may differ from the Gregorian year near year boundaries),iso_weekis the week number in the range1..=53,weekdayis aWeekdayvalue (Monday-based week).
Follows the ISO 8601 standard: weeks start on Monday and week 1 is the week containing January 4.
The optional ymd argument is a performance optimization. If provided,
it is used directly; otherwise to_gregorian_ymd
is called internally.
Sourcepub const fn days_in_month(yr: i64, mo: u8) -> u8
pub const fn days_in_month(yr: i64, mo: u8) -> u8
Number of days in a month under proleptic Gregorian rules.
Sourcepub const fn clamp_mdhms(
yr: i64,
mo: u8,
day: u8,
hr: u8,
min: u8,
sec: u8,
) -> (u8, u8, u8, u8, u8)
pub const fn clamp_mdhms( yr: i64, mo: u8, day: u8, hr: u8, min: u8, sec: u8, ) -> (u8, u8, u8, u8, u8)
Clamps month, day, hour, minutes, and seconds values. Clamps days to what is correct for that particular propleptic gregorian month.
For example the year 2000 is a leap year, and February in that year has 29 days so the days are clamped to 1-29 in that year, but 1-28 in non-leap years.
Source§impl Dt
impl Dt
Sourcepub const fn to_jd(&self) -> (i64, u128)
pub const fn to_jd(&self) -> (i64, u128)
Returns the exact Julian Date of this instant as (integer_days, fractional_attoseconds).
- The returned JD is expressed in the time scale of this
Dt. - The fractional part is always in
[0, ATTOS_PER_DAY).
For a float value use Self::to_jd_f.
Sourcepub const fn to_jd_f(&self) -> Real
pub const fn to_jd_f(&self) -> Real
Returns the Julian Date of this instant as a floating-point Real.
This is the lossy counterpart to Self::to_jd.
Sourcepub const fn to_mjd(&self) -> (i64, u128)
pub const fn to_mjd(&self) -> (i64, u128)
Returns the exact Modified Julian Date of this instant as (integer_days, fractional_attoseconds).
- The returned MJD is expressed in the time scale of this
Dt. - The fractional part is always in
[0, ATTOS_PER_DAY).
For a float value use Self::to_mjd_f.
Sourcepub const fn to_mjd_f(&self) -> Real
pub const fn to_mjd_f(&self) -> Real
Returns the Modified Julian Date of this instant as a floating-point Real.
This is the lossy counterpart to Self::to_mjd.
Sourcepub const fn from_jd(jd_days: i64, frac_attos: u128, on: Scale) -> Dt
pub const fn from_jd(jd_days: i64, frac_attos: u128, on: Scale) -> Dt
Creates a Dt from an exact Julian Date.
This is the inverse of Self::to_jd. For correct round-tripping you must
pass the same on: Scale that matches the scale of the original Dt.
Sourcepub const fn from_mjd(mjd_days: i64, frac_attos: u128, on: Scale) -> Dt
pub const fn from_mjd(mjd_days: i64, frac_attos: u128, on: Scale) -> Dt
Creates a Dt from an exact Modified Julian Date.
This is the inverse of Self::to_mjd. For correct round-tripping you must
pass the same on: Scale that matches the scale of the original Dt.
Sourcepub const fn from_jd_f(jd: Real, on: Scale) -> Dt
pub const fn from_jd_f(jd: Real, on: Scale) -> Dt
Creates a Dt from a float Julian Date.
This is the inverse of Self::to_jd_f. For correct round-tripping you must
pass the same on: Scale that matches the scale of the original Dt.
Sourcepub const fn from_mjd_f(mjd: Real, on: Scale) -> Dt
pub const fn from_mjd_f(mjd: Real, on: Scale) -> Dt
Creates a Dt from a float Modified Julian Date.
This is the inverse of Self::to_mjd_f. For correct round-tripping you must
pass the same on: Scale that matches the scale of the original Dt.
Source§impl Dt
impl Dt
Sourcepub const fn cmp(&self, other: &Self) -> Ordering
pub const fn cmp(&self, other: &Self) -> Ordering
Compares the time values represented by two Dts.
- This comparison is based on the total attosecond value (
self.attosvsother.attos). - Does not perform scale conversion.
Sourcepub const fn min(self, other: Self) -> Self
pub const fn min(self, other: Self) -> Self
Returns the smaller of two Dts according to the total physical-time order
defined by Self::cmp.
This is a const fn and can be used in const contexts.
Sourcepub const fn eq(&self, other: &Self) -> bool
pub const fn eq(&self, other: &Self) -> bool
True if both sides have the same total attosecond value.
This is a const fn so it can be used in const contexts.
Sourcepub const fn lt(&self, other: &Self) -> bool
pub const fn lt(&self, other: &Self) -> bool
Returns true if this Dt is less than the other.
This is a const fn so it can be used in const contexts.
Sourcepub const fn gt(&self, other: &Self) -> bool
pub const fn gt(&self, other: &Self) -> bool
Returns true if this Dt is greater than the other.
This is a const fn so it can be used in const contexts.
Source§impl Dt
impl Dt
Sourcepub const fn tdb_minus_tt(seconds_since_j2000_tt: Real) -> Real
pub const fn tdb_minus_tt(seconds_since_j2000_tt: Real) -> Real
DE440/LTE440-tuned compact analytical TT–TDB model
Exact 13-term Fourier decomposition from LTE440 (Lu et al. 2025, Table 3)
- physical VSOP2013 annual term + tiny JPL secular corrections.
Sourcepub const fn tai_to_tdb(tai: Dt) -> Dt
pub const fn tai_to_tdb(tai: Dt) -> Dt
Converts a TAI Dt to TDB.
Sourcepub const fn tdb_to_tai(tdb: Dt) -> Dt
pub const fn tdb_to_tai(tdb: Dt) -> Dt
Converts a TDB Dt to TAI.
Source§impl Dt
impl Dt
Sourcepub const CCSDS_C_AND_D_MAX_SIZE: usize = 32
pub const CCSDS_C_AND_D_MAX_SIZE: usize = 32
Maximum size needed for a CCSDS C & D (CUC) binary packet (with extended P-field).
Sourcepub const CCSDS_CCS_MAX_SIZE: usize = 14
pub const CCSDS_CCS_MAX_SIZE: usize = 14
Maximum size needed for a CCSDS CCS binary packet (P-field + T-field).
Sourcepub fn to_ccsds_c(
&self,
n_coarse: u8,
n_frac: u8,
extension: bool,
) -> Result<([u8; 32], usize), DtErr>
pub fn to_ccsds_c( &self, n_coarse: u8, n_frac: u8, extension: bool, ) -> Result<([u8; 32], usize), DtErr>
Formats this Dt as a CCSDS C (CUC) binary time code.
Fully configurable for round-tripping with [from_ccsds_c].
Conforms to CCSDS 301.0-B-4 §3.2 (Level 1), including full support for the
extended P-field (second octet) when n_coarse > 4 or n_frac > 3.
§Parameters
n_coarse: 1–7 (number of coarse-time octets)n_frac: 0–10 (number of fractional octets)extension: advisory flag (ignored when larger sizes force the second octet)
Sourcepub fn to_ccsds_d(
&self,
n_day: u8,
sub_ms_code: u8,
extension: bool,
) -> Result<([u8; 32], usize), DtErr>
pub fn to_ccsds_d( &self, n_day: u8, sub_ms_code: u8, extension: bool, ) -> Result<([u8; 32], usize), DtErr>
Formats this Dt as a CCSDS D (CDS) binary time code.
- Fully configurable for round-tripping with [
from_ccsds_d]. - Conforms to CCSDS 301.0-B-4 §3.3 (Level 1): UTC day count + ms-of-day since 1958-01-01 UTC.
Sourcepub fn to_ccsds_ccs(
&self,
use_doy: bool,
n_subsec: u8,
) -> Result<([u8; 14], usize), DtErr>
pub fn to_ccsds_ccs( &self, use_doy: bool, n_subsec: u8, ) -> Result<([u8; 14], usize), DtErr>
Formats this Dt as a CCSDS CCS (Calendar Segmented Time Code).
Implements CCSDS 301.0-B-4 §3.4 (Level 1 only).
§Parameters
use_doy:false= Month/Day variant (most common),true= Day-of-Year variantn_subsec: Number of subsecond BCD octets (0–6). Each octet holds 2 decimal digits.
§Returns
(buffer, written_len) — the P-field + T-field (big-endian BCD).
§Precision & Rounding
Fractional seconds are rounded to the nearest representable value at the chosen precision
(exactly as to_ccsds_d does for milliseconds).
Source§impl Dt
impl Dt
Sourcepub fn to_iso_duration(&self) -> String
pub fn to_iso_duration(&self) -> String
Converts this Dt to an ISO 8601 duration string
(e.g. "PT1H23M45.6789S", "-PT0.5S", "PT0.000000000000000001S", or "PT0S").
- This method is only available when the
allocfeature is enabled. - It returns
alloc::string::String(no_std + alloc compatible). - Performs no time scale conversions prior to output.
Sourcepub fn to_str(&self, fmt: &str) -> Result<String, DtErr>
pub fn to_str(&self, fmt: &str) -> Result<String, DtErr>
Formats this Dt into a String. Requires the "alloc" feature.
Converts from the Dts current time scale to the Dts target
time scale before producing the result.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
let s = x.to_str("%F").unwrap();
println!("{}", s);§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn to_str_with_offset(&self, fmt: &str, secs: i32) -> Result<String, DtErr>
pub fn to_str_with_offset(&self, fmt: &str, secs: i32) -> Result<String, DtErr>
Formats this Dt into a String, applying a fixed UTC offset. Requires the
"alloc" feature.
- A copy of the
Dtis adjusted by the givensecsoffset before formatting, and the offset is stored so that%z/%:zformat directives will reflect it. - Converts from the
Dts current timescaleto theDtstargettime scale before producing the result. - No IANA timezone name or abbreviation is set.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
// offset of minus one hour
let s = x.to_str_with_offset("%F", -3600).unwrap();
println!("{}", s);§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn to_str_with_tz(&self, fmt: &str, tz_name: &str) -> Result<String, DtErr>
pub fn to_str_with_tz(&self, fmt: &str, tz_name: &str) -> Result<String, DtErr>
Formats this Dt into a string, time adjusted to the given IANA timezone. Requires
the "alloc" feature.
Use this method when you want full IANA-aware formatting (%Q, %Z, %z, etc.).
- A copy of the
Dtis adjusted by the offset at theDts time for the given IANA timezone. This is so that the formatter will have:- Accurate wall time for the timezone.
- Correct numeric offset (for
%z/%:z). - Timezone abbreviation (for
%Z). These do not round-trip. - Full IANA timezone name (for
%Q/%:Q).
- Converts from the
Dts current timescaleto theDtstargettime scale before producing the result. - No IANA timezone name or abbreviation is set.
§Examples
use deep_time::{Dt, Scale};
let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
let s = x.to_str_with_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York").unwrap();
assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn to_str_rfc3339(&self) -> Result<String, DtErr>
pub fn to_str_rfc3339(&self) -> Result<String, DtErr>
Returns this instant as an RFC 3339 / ISO 8601 timestamp with a
Z suffix.
Sourcepub fn to_str_rfc3339_nf(&self, max_precision: usize) -> Result<String, DtErr>
pub fn to_str_rfc3339_nf(&self, max_precision: usize) -> Result<String, DtErr>
Same as Dt::to_str_rfc3339 but
with a configurable maximum number of fractional digits (0–18). Trailing zeros are
always trimmed.
Converts from the Dts current time scale to the Dts target
time scale before producing the result.
Sourcepub fn to_str_iso8601(&self) -> Result<String, DtErr>
pub fn to_str_iso8601(&self) -> Result<String, DtErr>
ISO 8601 / RFC 3339 with actual offset (modern +00:00 style).
Sourcepub fn to_str_iso8601_basic(&self) -> Result<String, DtErr>
pub fn to_str_iso8601_basic(&self) -> Result<String, DtErr>
Sourcepub fn to_str_http(&self) -> Result<String, DtErr>
pub fn to_str_http(&self) -> Result<String, DtErr>
Sourcepub fn to_str_rfc2822(&self) -> Result<String, DtErr>
pub fn to_str_rfc2822(&self) -> Result<String, DtErr>
Sourcepub fn to_str_iso_week_date(&self) -> Result<String, DtErr>
pub fn to_str_iso_week_date(&self) -> Result<String, DtErr>
Sourcepub fn to_str_iso_date(&self) -> Result<String, DtErr>
pub fn to_str_iso_date(&self) -> Result<String, DtErr>
Source§impl Dt
impl Dt
Sourcepub fn to_str_bin(&self, fmt: &str) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
pub fn to_str_bin(&self, fmt: &str) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
Formats this Dt into a fixed-size binary string.
Converts from the Dts current time scale to the Dts target
time scale before producing the result.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
let b = x.to_str_bin("%F").unwrap();
let s = b.as_str().unwrap();
println!("{}", s);§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn to_str_bin_with_offset(
&self,
fmt: &str,
secs: i32,
) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
pub fn to_str_bin_with_offset( &self, fmt: &str, secs: i32, ) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
Formats this Dt into a fixed-size binary string, applying a fixed UTC offset.
- A copy of the
Dtis adjusted by the givensecsoffset before formatting, and the offset is stored so that%z/%:zformat directives will reflect it. - No IANA timezone name or abbreviation is set.
- Converts from the
Dts current timescaleto theDtstargettime scale before producing the result.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
// offset of minus one hour
let b = x.to_str_bin_with_offset("%F", -3600).unwrap();
let s = b.as_str().unwrap();
println!("{}", s);§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn to_str_bin_with_tz(
&self,
fmt: &str,
tz_name: &str,
) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
pub fn to_str_bin_with_tz( &self, fmt: &str, tz_name: &str, ) -> Result<LiteStr<STRFTIME_SIZE>, DtErr>
Formats this Dt into a fixed-size binary string, time adjusted to the given
IANA timezone.
Use this method when you want full IANA-aware formatting (%Q, %Z, %z, etc.).
- A copy of the
Dtis adjusted by the offset at theDts time for the given IANA timezone. This is so that the formatter will have:- Accurate wall time for the timezone.
- Correct numeric offset (for
%z/%:z). - Timezone abbreviation (for
%Z). These do not round-trip. - Full IANA timezone name (for
%Q/%:Q).
- No IANA timezone name or abbreviation is set.
- Converts from the
Dts current timescaleto theDtstargettime scale before producing the result.
§Examples
use deep_time::{Dt, Scale};
let x = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
let b = x.to_str_bin_with_tz("%F", "America/New_York").unwrap();
let s = b.as_str().unwrap();
println!("{}", s);§Errors
Returns DtErr if the format string contains invalid specifiers
or if the internal formatting buffer overflows (extremely unlikely
with STRFTIME_SIZE).
§See also
Sourcepub fn _to_u8_with_offset(
&self,
fmt: &str,
dest: &mut [u8],
secs: i32,
) -> Result<usize, DtErr>
pub fn _to_u8_with_offset( &self, fmt: &str, dest: &mut [u8], secs: i32, ) -> Result<usize, DtErr>
Low-level no-alloc formatter that writes into a caller-provided slice, using a fixed UTC offset.
Same logic as
Dt::to_str_bin_with_offset
but writes directly into dest (truncated to dest.len()) and returns the
number of bytes written.
Sourcepub fn _to_u8_with_tz(
&self,
fmt: &str,
dest: &mut [u8],
tz_name: &str,
) -> Result<usize, DtErr>
pub fn _to_u8_with_tz( &self, fmt: &str, dest: &mut [u8], tz_name: &str, ) -> Result<usize, DtErr>
Low-level no-alloc formatter that writes into a caller-provided slice, using a full IANA timezone.
Same logic as
Dt::to_str_bin_with_tz
but writes directly into dest (truncated to dest.len()) and returns the
number of bytes written.
Source§impl Dt
impl Dt
Sourcepub fn proper_time_from_states<I>(
samples: I,
characteristic_length_scale: Real,
) -> Result<Self, DtErr>
pub fn proper_time_from_states<I>( samples: I, characteristic_length_scale: Real, ) -> Result<Self, DtErr>
Computes the relativistic clock drift (proper time minus coordinate time) over an interval.
This returns how much a physical clock has gained or lost time compared
with coordinate time between start and end.
- A positive result means the onboard clock ran fast.
- A negative result means the onboard clock ran slow.
§Parameters
start: Starting coordinate time of the interval.end: Ending coordinate time of the interval.states: Iterator of physical states. Coordinate times must be monotonically non-decreasing. It is the caller’s responsibility to ensure the provided states cover the time range fromstarttoend. The function integrates proper time over whatever states are supplied and subtracts the requested coordinate interval (end - start). Exact matching of the first and last state times tostartandendis not validated.characteristic_length_scale: See [proper_time_from_states].
§Returns
Ok(drift) — the accumulated drift (Δτ − Δt) as a Dt.
Err(DtErr) — if the states are not monotonically increasing in time.
Sourcepub fn proper_time_drift_from_states<I>(
start: Dt,
end: Dt,
states: I,
characteristic_length_scale: Real,
) -> Result<Dt, DtErr>
pub fn proper_time_drift_from_states<I>( start: Dt, end: Dt, states: I, characteristic_length_scale: Real, ) -> Result<Dt, DtErr>
Computes the relativistic clock drift (proper time minus coordinate time) over an interval.
This returns how much a physical clock has gained or lost time compared
with coordinate time between start and end.
- A positive result means the onboard clock ran fast.
- A negative result means the onboard clock ran slow.
§Parameters
start: Starting coordinate time.end: Ending coordinate time.states: Iterator of physical states covering the interval. Coordinate times must be monotonically non-decreasing. It is the caller’s responsibility to ensure the states span the requested interval (exact first/last time matching is not checked).characteristic_length_scale: See [proper_time_from_states].
§Returns
Ok(drift) — the accumulated drift (Δτ − Δt) as a Dt.
Err(DtErr) — if the states are not monotonically increasing in time.
Sourcepub fn proper_time_from_path<I>(path: I) -> Result<Self, DtErr>where
I: IntoIterator<Item = (Self, Spacetime)>,
pub fn proper_time_from_path<I>(path: I) -> Result<Self, DtErr>where
I: IntoIterator<Item = (Self, Spacetime)>,
Computes accumulated proper time along an arbitrary trajectory.
This is the core integration function of the library. It walks the supplied path segment by segment and applies the trapezoidal rule to the instantaneous proper-time rate at each step.
This approach is commonly used when integrating clock rates along sampled trajectories in astrodynamics and high-precision timing work.
The function enforces that coordinate times are monotonically non-decreasing. It performs a single pass with no heap allocation.
§Parameters
path: An iterator of(coordinate_time, Spacetime)pairs. Coordinate times must be monotonically non-decreasing.
§Returns
Ok(total_proper_time) — the accumulated proper time as a Dt.
Err(DtErr) — if the path is empty or contains any decrease in
coordinate time.
Sourcepub const fn proper_time_between_constant_rate(
self,
end: Dt,
dtau_dt: Real,
) -> Dt
pub const fn proper_time_between_constant_rate( self, end: Dt, dtau_dt: Real, ) -> Dt
Computes proper time advance over an interval when the rate is constant.
Use this for segments where conditions do not change, such as a ground station, a circular orbit, or a deep-space cruise phase with constant velocity and gravitational potential.
This is mathematically equivalent to integrating a constant rate but is more efficient and expresses intent clearly.
§Parameters
end: Ending coordinate time.dtau_dt: Constant proper-time rate (dimensionless, usually between 0 and 1).
§Returns
The accumulated proper time advance as a Dt.
Source§impl Dt
impl Dt
Sourcepub fn to_str_ccsds(&self) -> Result<String, DtErr>
pub fn to_str_ccsds(&self) -> Result<String, DtErr>
Returns this instant as a CCSDS ASCII Time Code (calendar variant A).
Example: "2025-04-17T14:30:45.123456789Z"
- Uses
Tseparator and trailingZ. - Fractional seconds are trimmed (no trailing zeros, no dot if zero).
- Perfect round-trip with
Dt::from_str_ccsds/TimeParts::from_str_ccsds.
Sourcepub fn to_str_ccsds_nf(&self, max_precision: usize) -> Result<String, DtErr>
pub fn to_str_ccsds_nf(&self, max_precision: usize) -> Result<String, DtErr>
Same as [to_str_ccsds] but lets you control the maximum number of fractional digits (0–18).
Sourcepub fn to_ccsds_doy_str(&self) -> Result<String, DtErr>
pub fn to_ccsds_doy_str(&self) -> Result<String, DtErr>
Returns this instant as a CCSDS ASCII Time Code B (day-of-year variant).
Example: "2025-107T14:30:45.123456789Z"
Source§impl Dt
impl Dt
Sourcepub const fn to_msd(&self) -> (i64, u128)
pub const fn to_msd(&self) -> (i64, u128)
Returns the Mars Sol Date (MSD) as a tuple of integer sols and the fractional part of a sol.
- The computation follows the canonical NASA GISS / AM2000 formulation and works for any input
Scale. - Leap seconds are automatically accounted for when converting from UTC.
Sourcepub const fn to_mtc(&self) -> Dt
pub const fn to_mtc(&self) -> Dt
Returns Mars Coordinated Time (MTC) as a Dt representing
seconds into the current sol (range [0, one Martian sol)).
Sourcepub const fn from_msd(whole_sols: i64, frac_attos: u128) -> Dt
pub const fn from_msd(whole_sols: i64, frac_attos: u128) -> Dt
Creates a Dt (in TT) from an Mars Sol Date using full library precision.
Sourcepub const fn from_msd_f(msd: Real) -> Dt
pub const fn from_msd_f(msd: Real) -> Dt
Creates a Dt (in TT) from a floating-point Mars Sol Date.
Non-exact Real.
Sourcepub const fn to_msd_f(&self) -> Real
pub const fn to_msd_f(&self) -> Real
Returns the Mars Sol Date (MSD) as a floating-point value (matches NASA Mars24 output). Non-exact Real.
Sourcepub const fn to_mars_ls(&self) -> Real
pub const fn to_mars_ls(&self) -> Real
Returns the Areocentric Solar Longitude Ls in degrees (range [0, 360)).
Ls is the angular position of the Sun as measured eastward from the Martian vernal equinox in Mars’s orbital plane. It is the standard index of Martian seasonal progression used in all mission planning, science operations, and atmospheric modeling. Due to orbital eccentricity, northern spring + summer last ~381 Earth days while autumn + winter last ~306 Earth days.
- Ls = 0° → northern vernal equinox (northern spring begins)
- Ls = 90° → northern summer solstice
- Ls = 180° → northern autumnal equinox
- Ls = 270° → northern winter solstice
Reproduces the short-series analytic model (B-1 through B-5) used by the current NASA GISS Mars24 Sunclock algorithm, which is based on Allison & McEwen (2000) with the seven largest planetary perturbations.
Source: NASA Goddard Institute for Space Studies (GISS)
Title: Mars24 Sunclock — Algorithm and Worked Examples
URL: https://www.giss.nasa.gov/tools/mars24/help/algorithm.html
Updated: 2025-01-07
Works for any input Scale because it internally converts to TT.
Sourcepub const fn to_mars_lmst(&self, east_longitude_deg: Real) -> Dt
pub const fn to_mars_lmst(&self, east_longitude_deg: Real) -> Dt
Returns Local Mean Solar Time (LMST) at the given planetocentric east longitude
as a Dt representing seconds into the current Martian sol (range [0, one sol)).
LMST is the uniform mean solar time adjusted for longitude.
Longitude is east-positive (standard planetocentric convention, 0–360° E). Internally converts to TT and uses the current NASA GISS Mars24 definition of MST.
Sourcepub const fn to_mars_ltst(&self, east_longitude_deg: Real) -> Dt
pub const fn to_mars_ltst(&self, east_longitude_deg: Real) -> Dt
Returns Local True Solar Time (LTST) at the given planetocentric east longitude
as a Dt representing seconds into the current Martian sol (range [0, one sol)).
LTST is the actual sundial time (true solar time) at the location — what a local observer would see on a sundial. It equals LMST plus the Equation of Time.
Longitude is east-positive (standard planetocentric convention, 0–360° E).
Sourcepub const fn to_mars_year(&self) -> i64
pub const fn to_mars_year(&self) -> i64
Returns the integer Mars Year (MY) for this instant.
Mars Year numbering follows the standard Clancy et al. (2000) system:
- Mars Year 1 begins at the northern vernal equinox (Ls = 0°) on 1955 April 11.
- Each Mars Year is one tropical year on Mars (686.9725 Earth days).
- Current missions operate in Mars Year 36–37 (as of 2026).
This is the canonical year count used in all Mars science literature, mission reports, and atmospheric databases.
Source: Clancy et al. (2000), J. Geophys. Res.: Planets 105(E4), 9553–9572; confirmed in NASA GISS Mars24 Technical Notes (2025) and LMD Mars Climate Database.
To get the fractional progress through the year, simply use:
self.to_mars_ls(current) / 360.0
Source§impl Dt
impl Dt
Sourcepub fn to_hifitime_epoch(&self) -> Epoch
pub fn to_hifitime_epoch(&self) -> Epoch
Converts this Dt to a hifitime::Epoch (TAI scale).
Round-trips with [Dt::from_hifitime].
Sourcepub fn from_hifitime_epoch(epoch: Epoch) -> Dt
pub fn from_hifitime_epoch(epoch: Epoch) -> Dt
Creates a Dt from a hifitime::Epoch.
- The conversion is exact (within hifitime’s nanosecond precision).
- Uses a runtime-computed offset so it always matches whatever calendar math hifitime uses (including negative years).
Sourcepub fn to_hifitime_duration(&self) -> Duration
pub fn to_hifitime_duration(&self) -> Duration
Converts this Dt to a hifitime::Duration (nanosecond precision).
- Sub-nanosecond attoseconds are truncated toward zero.
- The conversion is exact up to the nanosecond (128-bit integer arithmetic).
- Internally uses
hifitime::Duration::from_total_nanoseconds, which automatically normalizes centuries/nanoseconds and saturates atDuration::MAX/Duration::MINif outside hifitime’s range (±32,768 centuries).
Sourcepub fn from_hifitime_duration(dur: Duration) -> Dt
pub fn from_hifitime_duration(dur: Duration) -> Dt
Creates a Dt from a hifitime::Duration (nanosecond precision).
Inverse of Dt::to_hifitime_duration.
Source§impl Dt
impl Dt
Sourcepub fn to_chrono_datetime_utc(&self) -> DateTime<Utc>
pub fn to_chrono_datetime_utc(&self) -> DateTime<Utc>
Converts this Dt to a chrono::DateTime.
- Sub-nanosecond attoseconds are truncated toward zero.
- Saturates at the minimum/maximum representable
DateTime<Utc>(roughly years 1678–2262) if the instant is out of range.
Sourcepub fn from_chrono_datetime_utc(dt: DateTime<Utc>) -> Dt
pub fn from_chrono_datetime_utc(dt: DateTime<Utc>) -> Dt
Creates a TAI Dt from a chrono::DateTime.
This is the inverse of Dt::to_chrono_datetime_utc.
Sourcepub fn from_chrono_duration(dur: Duration) -> Dt
pub fn from_chrono_duration(dur: Duration) -> Dt
Creates a Dt from a chrono::Duration (nanosecond precision).
Sourcepub fn to_chrono_duration(&self) -> Duration
pub fn to_chrono_duration(&self) -> Duration
Converts this Dt to a chrono::Duration (nanosecond precision).
- Sub-nanosecond attoseconds are truncated toward zero.
- The conversion is fully exact up to the nanosecond (128-bit integer arithmetic).
- Saturates at
chrono::Duration::MIN/chrono::Duration::MAX(roughly ±292 million years) if the value is out of range.
Source§impl Dt
impl Dt
Sourcepub fn to_jiff_timestamp(&self) -> Timestamp
pub fn to_jiff_timestamp(&self) -> Timestamp
Converts this Dt to a jiff::Timestamp.
Sourcepub fn to_jiff_span(&self) -> Span
pub fn to_jiff_span(&self) -> Span
Converts this Dt to a jiff::Span (seconds + nanoseconds only).
Sourcepub fn to_jiff_signed_duration(&self) -> SignedDuration
pub fn to_jiff_signed_duration(&self) -> SignedDuration
Converts this Span to a jiff::SignedDuration (nanosecond precision).
- Sub-nanosecond attoseconds are truncated toward zero.
- Supports the entire range of
Span(never saturates).
Sourcepub fn from_jiff_timestamp(ts: Timestamp) -> Dt
pub fn from_jiff_timestamp(ts: Timestamp) -> Dt
Creates a Dt from a jiff::Timestamp.
This is the inverse of Dt::to_jiff_timestamp.
Sourcepub fn from_jiff_signed_duration(dur: SignedDuration) -> Dt
pub fn from_jiff_signed_duration(dur: SignedDuration) -> Dt
Creates a Dt from a jiff::SignedDuration (nanosecond precision).
This is the inverse of Dt::to_jiff_signed_duration.
Sourcepub fn from_jiff_span(span: Span) -> Result<Self, DtErr>
pub fn from_jiff_span(span: Span) -> Result<Self, DtErr>
Creates a Dt from a jiff::Dt.
This is the inverse of Dt::to_jiff_span.
Source§impl Dt
impl Dt
Sourcepub const SHAPIRO_SOLAR: Self
pub const SHAPIRO_SOLAR: Self
Shapiro gravitational time scale for the Sun (2 G M_☉ / c³).
Recommended value for the Sun when building the bodies slice passed to
ObserverState::shapiro_delay, ObserverState::shapiro_delay,
and related methods.
Sourcepub const fn shapiro_from_grav_param(gm: Real) -> Dt
pub const fn shapiro_from_grav_param(gm: Real) -> Dt
Creates the Shapiro delay scale for an arbitrary central body
from its standard gravitational parameter GM (μ) in m³ s⁻².
This produces the coefficient used in the Shapiro gravitational time delay formula. It is the recommended way to create a custom Shapiro scale for planets, stars, or other massive bodies.
The returned value is intended to be used for the bodies parameter
when calling ObserverState::shapiro_delay or
ObserverState::shapiro_delay.
Sourcepub const fn to_observer_state(
self,
position: Position,
velocity: Velocity,
grav_potential_m2_s2: Real,
characteristic_length_scale: Real,
) -> ObserverState
pub const fn to_observer_state( self, position: Position, velocity: Velocity, grav_potential_m2_s2: Real, characteristic_length_scale: Real, ) -> ObserverState
Creates an ObserverState using this time value along with the
provided position, velocity, and gravitational information.
An ObserverState represents a complete snapshot of an observer
(spacecraft, ground station, planet, etc.) at a specific moment.
It bundles together the time, position, velocity, and local
gravitational environment so that relativistic calculations
(light time, clock rates, Shapiro delay, etc.) can be performed.
This method is a convenience constructor. It is useful when you
already have a Dt (a time value) and want to build an
ObserverState directly from it, rather than calling
ObserverState::new or [ObserverState::new_strong_field].
§Parameters
position: The observer’s position in meters (typically expressed in a barycentric or heliocentric frame).velocity: The observer’s velocity in meters per second.grav_potential_m2_s2: The total Newtonian gravitational potential (Φ) at the observer’s location, in m²/s². This is usually negative for bound orbits and is the sum of contributions from the Sun and planets.characteristic_length_scale: A length scale (in meters) over which gravity varies significantly at this location. Use0.0for normal solar-system and weak-field cases. Only provide a non-zero value when working in strong gravitational fields.
§When to use this method
Use this method when you already have a time value as a Dt and
want to construct an ObserverState in one step. It is especially
convenient when working with time values that were previously
computed or converted.
For most normal use, ObserverState::new is simpler. Use
[ObserverState::new_strong_field] instead if you need to specify
a non-zero characteristic_length_scale.
§Examples
let t = Dt::from_sec(1234.5);
let state = t.to_observer_state(
position,
velocity,
grav_potential,
0.0, // normal solar-system use
);Source§impl Dt
impl Dt
Sourcepub const fn every(self, step: Dt) -> Every
pub const fn every(self, step: Dt) -> Every
Starts building an evenly-spaced time range.
This method returns an Every builder that can be chained with
.until(end) or .up_to(end) to create a TimeRange iterator.
§Examples
use deep_time::{Dt, Scale};
let start = Dt::from_ymd(2000, 1, 1, 0, 0, 0, 0, Scale::UTC);
let end = Dt::from_ymd(2000, 1, 2, 0, 0, 0, 0, Scale::UTC);
let step = Dt::from_hr(1, Scale::TAI);
for timestamp in start.every(step).to_including(end) {
println!("{:?}", timestamp.to_ymd());
}Sourcepub const fn range(self, end: Dt, step: Dt) -> TimeRange ⓘ
pub const fn range(self, end: Dt, step: Dt) -> TimeRange ⓘ
Creates an exclusive evenly-spaced range from self to end.
Equivalent to self.every(step).up_to(end).
Sourcepub fn next_n(self, n: usize, step: Dt) -> impl ExactSizeIterator<Item = Dt>
pub fn next_n(self, n: usize, step: Dt) -> impl ExactSizeIterator<Item = Dt>
Returns the next n points after self (exclusive of self)
at the given step.
This is a convenient way to get future points without including the start.
Sourcepub fn for_n_steps(
self,
n: usize,
step: Dt,
) -> impl ExactSizeIterator<Item = Dt>
pub fn for_n_steps( self, n: usize, step: Dt, ) -> impl ExactSizeIterator<Item = Dt>
Returns an iterator yielding exactly n evenly spaced points
starting from self.
This is a convenient one-liner for the common “next N steps” pattern.
Source§impl Dt
impl Dt
Source§impl Dt
impl Dt
Sourcepub fn leap_sec_data_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<LeapSec>>
pub fn leap_sec_data_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<LeapSec>>
Load directly from a file (e.g. the official IANA leap-seconds.list).
Format should be the same as the file available at: https://data.iana.org/time-zones/data/leap-seconds.list
For rows that don’t start with # (the data rows) the first column should be the NTP timestamp, the second column (separated by whitespace) should be the offset against TAI in seconds (the number of leap seconds at that point).
e.g.
| #NTP Time | DTAI |
|---|---|
| # | |
| 2272060800 | 10 |
| 2287785600 | 11 |
| 2303683200 | 12 |
Source§impl Dt
impl Dt
Sourcepub fn leap_sec_data_from_str(s: &str) -> Vec<LeapSec>
pub fn leap_sec_data_from_str(s: &str) -> Vec<LeapSec>
Load directly from a str (e.g. the official IANA leap-seconds.list).
Format should be the same as the file available at: https://data.iana.org/time-zones/data/leap-seconds.list
For rows that don’t start with # (the data rows) the first column should be the NTP timestamp, the second column (separated by whitespace) should be the offset against TAI in seconds (the number of leap seconds at that point).
e.g.
| #NTP Time | DTAI |
|---|---|
| # | |
| 2272060800 | 10 |
| 2287785600 | 11 |
| 2303683200 | 12 |
§Examples
let table = Self::leap_sec_from_str(&file_content_as_str);Source§impl Dt
impl Dt
Sourcepub fn mjd_to_eop_offset(
mjd: Real,
op_data: &EopData,
) -> Result<EopOffset, DtErr>
pub fn mjd_to_eop_offset( mjd: Real, op_data: &EopData, ) -> Result<EopOffset, DtErr>
Get an orientation parameters offset in seconds inside a struct: (EopOffset)
for a particular Modified Julian Date.
- On Earth this would be the UT1 time scale.
- Earth Orientation Parameters data is available from: https://maia.usno.navy.mil/ser7/finals2000A.all
Sourcepub fn mjd_to_eop_offset_f(mjd: Real, op_data: &EopData) -> Result<Real, DtErr>
pub fn mjd_to_eop_offset_f(mjd: Real, op_data: &EopData) -> Result<Real, DtErr>
Get an orientation parameters offset in seconds for a particular Modified Julian Date.
- On Earth this would be the UT1 time scale.
- Earth Orientation Parameters data is available from: https://maia.usno.navy.mil/ser7/finals2000A.all
Sourcepub fn to_eop(&self, op_data: &EopData) -> Result<Self, DtErr>
pub fn to_eop(&self, op_data: &EopData) -> Result<Self, DtErr>
Offsets a Dt using orientation parameters data.
- On Earth this would be the UT1 time scale.
- Earth Orientation Parameters data is available from: https://maia.usno.navy.mil/ser7/finals2000A.all
Sourcepub fn from_eop(&self, op_data: &EopData) -> Result<Self, DtErr>
pub fn from_eop(&self, op_data: &EopData) -> Result<Self, DtErr>
Convert a Dt already offset using orientation parameters data back to whatever
it was before.
- On Earth this would be the UT1 time scale.
- Earth Orientation Parameters data is available from: https://maia.usno.navy.mil/ser7/finals2000A.all
Trait Implementations§
Source§impl AddAssign for Dt
impl AddAssign for Dt
Source§fn add_assign(&mut self, rhs: Dt)
fn add_assign(&mut self, rhs: Dt)
+= operation. Read moreSource§impl<'de> Deserialize<'de> for Dt
impl<'de> Deserialize<'de> for Dt
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl DivAssign<f64> for Dt
impl DivAssign<f64> for Dt
Source§fn div_assign(&mut self, rhs: f64)
fn div_assign(&mut self, rhs: f64)
/= operation. Read moreSource§impl DivAssign<i64> for Dt
impl DivAssign<i64> for Dt
Source§fn div_assign(&mut self, rhs: i64)
fn div_assign(&mut self, rhs: i64)
Divides this Dt by an integer scalar in place.
Source§impl Hash for Dt
impl Hash for Dt
Source§impl MulAssign<f64> for Dt
impl MulAssign<f64> for Dt
Source§fn mul_assign(&mut self, rhs: f64)
fn mul_assign(&mut self, rhs: f64)
*= operation. Read moreSource§impl MulAssign<i64> for Dt
impl MulAssign<i64> for Dt
Source§fn mul_assign(&mut self, rhs: i64)
fn mul_assign(&mut self, rhs: i64)
Multiplies this Dt by an integer scalar in place.
Source§impl Ord for Dt
impl Ord for Dt
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialOrd for Dt
impl PartialOrd for Dt
Source§impl SubAssign for Dt
impl SubAssign for Dt
Source§fn sub_assign(&mut self, rhs: Dt)
fn sub_assign(&mut self, rhs: Dt)
-= operation. Read moreSource§impl Tsify for Dt
impl Tsify for Dt
const DECL: &'static str = "/**\n * **The library\\\'s central time type.** A high-precision instant/duration with attosecond\n * resolution.\n *\n * **Fields:**\n *\n * - pub attos: [`i128`] - total time in attoseconds since the reference epoch\n * (2000-01-01 noon), as a signed integer. Negative values represent times\n * before the epoch.\n * - pub scale: [`Scale`] - the current time scale of the object.\n * - pub target: [`Scale`] - a target time scale used by many output functions such as\n * [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) and\n * [`Dt::to_unix`](../struct.Dt.html#method.to_unix).\n *\n * **Notes:**\n *\n * - In theory it supports a range of roughly \u{b1}5.39 trillion years but many of the to and\n * from functions cap at i64 seconds, which can mean a range of \u{b1}292 billion years in practice.\n * - Implements `Copy` and `Clone`. Optional derives for `serde` and `tsify` are available\n * behind the corresponding features.\n * - A wide range of math is available for this type, but it\\\'s not calendar aware, for basic\n * calendar aware math use the [`YmdHms`] type.\n *\n * ## Reference epoch and scales\n *\n * - The librarys epoch for nearly all functionality such as the conversion functions is\n * **2000-01-01 noon**. See also: [`Scale`](../enum.Scale.html).\n * - Leap-second handling follows the chosen `Scale` (UTC, UtcSpice, UtcHist).\n *\n * ## See also (non-exhaustive list)\n *\n * ### From and to calendar dates\n *\n * - [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)\n * - [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd)\n * - [`Dt::to_ymd_rich`](../struct.Dt.html#method.to_ymd_rich)\n *\n * ### From and to str and bytes\n *\n * Some of these require the alloc feature, they\\\'re marked with *\n *\n * - [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse)*\n * - [`Dt::from_str_ccsds`](../struct.Dt.html#method.from_str_ccsds)\n * - [`Dt::parse`](../struct.Dt.html#method.parse)\n * - [`Dt::from_str`](../struct.Dt.html#method.from_str)\n * - [`Dt::to_str`](../struct.Dt.html#method.to_str)*\n * - [`Dt::to_str_with_offset`](../struct.Dt.html#method.to_str_with_offset)*\n * - [`Dt::to_str_with_tz`](../struct.Dt.html#method.to_str_with_tz)*\n * - [`Dt::to_str_iso8601`](../struct.Dt.html#method.to_str_iso8601)*\n * - [`Dt::to_str_bin`](../struct.Dt.html#method.to_str_bin)\n * - [`Dt::to_str_bin_with_offset`](../struct.Dt.html#method.to_str_bin_with_offset)\n * - [`Dt::to_str_bin_with_tz`](../struct.Dt.html#method.to_str_bin_with_tz)\n *\n * ### From and to julian dates\n *\n * - [`Dt::from_jd_f`](../struct.Dt.html#method.from_jd_f)\n * - [`Dt::from_mjd_f`](../struct.Dt.html#method.from_mjd_f)\n * - [`Dt::to_jd_f`](../struct.Dt.html#method.to_jd_f)\n * - [`Dt::to_mjd_f`](../struct.Dt.html#method.to_mjd_f)\n * - [`Dt::ymd_to_jd`](../struct.Dt.html#method.ymd_to_jd)\n * - [`Dt::jd_to_ymd`](../struct.Dt.html#method.jd_to_ymd)\n *\n * ### Conversions, time scales etc.\n *\n * - [`Dt::target`](../struct.Dt.html#method.target)\n * - [`Dt::from_sec`](../struct.Dt.html#method.from_sec)\n * - [`Dt::to_sec64`](../struct.Dt.html#method.to_sec64)\n * - [`Dt::from_attos`](../struct.Dt.html#method.from_attos)\n * - [`Dt::convert_internal`](../struct.Dt.html#method.convert_internal)\n * - [`Dt::to_unix`](../struct.Dt.html#method.to_unix)\n * - [`Dt::to_ntp`](../struct.Dt.html#method.to_ntp)\n * - [`Dt::to_gps_wk_and_tow`](../struct.Dt.html#method.to_gps_wk_and_tow)\n *\n * ### Conversions from and to types from other libraries\n *\n * - [`Dt::to_hifitime_epoch`](../struct.Dt.html#method.to_hifitime_epoch)\n * - [`Dt::to_jiff_timestamp`](../struct.Dt.html#method.to_jiff_timestamp)\n * - [`Dt::to_chrono_datetime_utc`](../struct.Dt.html#method.to_chrono_datetime_utc)\n * - [`Dt::from_hifitime_epoch`](../struct.Dt.html#method.from_hifitime_epoch)\n * - [`Dt::from_jiff_timestamp`](../struct.Dt.html#method.from_jiff_timestamp)\n * - [`Dt::from_chrono_datetime_utc`](../struct.Dt.html#method.from_chrono_datetime_utc)\n *\n * ## Examples\n *\n * ### Parsing a date\n *\n * ```\n * use deep_time::{Dt, Scale};\n *\n * // uses impl FromStr but Dt::parse provides the same functionality\n * let x: Dt = \\\"2000-01-01 12:00:00\\\".parse().unwrap();\n *\n * let ymd = x.to_ymd();\n * assert_eq!(ymd.yr(), 2000);\n * assert_eq!(ymd.mo(), 1);\n * assert_eq!(ymd.day(), 1);\n * assert_eq!(ymd.hr(), 12);\n * assert_eq!(ymd.min(), 0);\n * assert_eq!(ymd.sec(), 0);\n * assert_eq!(ymd.attos(), 0);\n * ```\n *\n * ### Outputting a date to string / bytes\n *\n * ```\n * # #[cfg(all(feature = \\\"tz\\\", feature = \\\"parse\\\"))]\n * # {\n * use deep_time::{Dt, Scale};\n *\n * let x: Dt = \\\"2000-01-01 12:00:00\\\".parse().unwrap();\n *\n * let s = x\n * .to_str_with_tz(\\\"%A, %B %d, %Y %H:%M:%S %Q\\\", \\\"America/New_York\\\")\n * .unwrap();\n * let b = x\n * .to_str_bin_with_tz(\\\"%A, %B %d, %Y %H:%M:%S %Q\\\", \\\"America/New_York\\\")\n * .unwrap();\n *\n * assert_eq!(s, \\\"Saturday, January 01, 2000 07:00:00 America/New_York\\\");\n * assert_eq!(b.as_str().unwrap(), \\\"Saturday, January 01, 2000 07:00:00 America/New_York\\\");\n * # }\n * ```\n *\n * ### Creating a unix timestamp in milliseconds\n *\n * ```\n * use deep_time::{Dt, Scale};\n *\n * // this fn converts from UTC and creates a TAI Dt\n * let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);\n *\n * // dt is internally TAI but has a UTC tag\n * let unix_ms = dt.to_unix().to_ms();\n *\n * // unix timestamp in ms for 2000-01-01 noon UTC\n * assert_eq!(unix_ms, 946728000000);\n * ```\n *\n * ### Converting time scales\n *\n * Many functions such as\n * [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) will convert to\n * `TAI` from the [`Dt`]s current `scale` then to the [`Dt`]s `target`\n * [`Scale`] prior to producing an output.\n *\n * So you don\\\'t necessarily have to convert time scales prior to using\n * many of the output functions. You just have to change the `target`\n * time scale.\n *\n * #### Using the target field\n *\n * ```\n * use deep_time::{Dt, Scale};\n *\n * // Leap seconds were added to the secounds count\n * // This Dt has attos that are now on the TAI timescale\n * let dt = Dt::from_ymd(2025, 1, 1, 0, 0, 0, 0, Scale::UTC);\n *\n * // The internal target is currently UTC so we don\\\'t need to do\n * // anything to output back to UTC and round trip\n * let bytes = dt.to_str_bin(\\\"%d %m %Y %H:%M:%S\\\").unwrap();\n *\n * assert_eq!(bytes.as_str().unwrap(), \\\"01 01 2025 00:00:00\\\");\n *\n * // Perhaps we want to make a GPS timestamp out of our Dt\n * // If we want it to be on the GPS time scale we have to set the\n * // target prior to calling to_gps()\n * let gps = dt.target(Scale::GPS).to_gps().to_sec_f();\n * ```\n *\n * #### Converting the internal attos to a new time scale\n *\n * ```\n * use deep_time::{Dt, Scale};\n *\n * // this fn converts from UTC and creates a TAI Dt\n * let dt = Dt::from_ymd(2000, 1, 1, 12, 0, 0, 0, Scale::UTC);\n *\n * // to tdb\n * let tdb = dt.to(Scale::TDB);\n *\n * // then to tt, the current scale is TDB\n * let tt = tdb.to(Scale::TT);\n *\n * // then back to TAI\n * let tai = tt.to(Scale::TAI);\n *\n * // round trip equality\n * assert_eq!(dt, tai);\n * ```\n *\n * ### Performing some basic calendar aware math\n *\n * ```\n * use deep_time::{Dt, Scale};\n *\n * let x = Dt::from_ymd(2000, 2, 29, 0, 0, 0, 0, Scale::UTC).to_ymd();\n * let x = x.add_yr(1);\n *\n * assert_eq!(x.day(), 28);\n * ```\n *\n * ### Changing a dates format\n *\n * ```\n * use deep_time::{Dt, StrPTimeFmt};\n *\n * let fmt = Dt::parse_fmt(\\\"%Y-%m-%dT%H:%M:%S\\\").unwrap();\n *\n * # #[cfg(feature = \\\"alloc\\\")]\n * let s = fmt.to_str(\\\"2000-01-01T12:00:00\\\", \\\"%d %m %Y %H:%M:%S\\\", false, false, false).unwrap();\n *\n * # #[cfg(feature = \\\"alloc\\\")]\n * assert_eq!(s, \\\"01 01 2000 12:00:00\\\", \\\"expected: {}, got: {}\\\", \\\"01 01 2000 12:00:00\\\", s);\n * ```\n */\nexport interface Dt {\n attos: number;\n scale: Scale;\n target: Scale;\n}"
const SERIALIZATION_CONFIG: SerializationConfig
type JsType = JsType
fn into_js(&self) -> Result<Self::JsType, Error>where
Self: Serialize,
fn from_js<T>(js: T) -> Result<Self, Error>
impl Copy for Dt
impl Eq for Dt
Auto Trait Implementations§
impl Freeze for Dt
impl RefUnwindSafe for Dt
impl Send for Dt
impl Sync for Dt
impl Unpin for Dt
impl UnsafeUnpin for Dt
impl UnwindSafe for Dt
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.