Package: hifitime
Introduction to HifitimeHifitime is a powerful Rust and Python library designed for time management. It provides extensive functionalities with precise operations for time calculation in different time scales, making it suitable for engineering and scientific applications where general relativity and time dilation matter. Hifitime guarantees nanosecond precision for 65,536 years around 01 January 1900 TAI. Hifitime is also formally verified using theKanimodel checker, read more about itthis verification here.Most users of Hifitime will only need to rely on theEpochandDurationstructures, and optionally theWeekdayenum for week based computations. Scientific applications may make use of theTimeScaleenum as well.UsageFirst, installhifitimeeither withcargo add hifitimein your Rust project orpip install hifitimein Python.If building from source, note that the Python package is only built if thepythonfeature is enabled.Epoch ("datetime" equivalent)Create an epoch in different time scales.usehifitime::prelude::*;usecore::str::FromStr;// Create an epoch in UTCletepoch=Epoch::from_gregorian_utc(2000,2,29,14,57,29,37);// Or from a stringletepoch_from_str=Epoch::from_str("2000-02-29T14:57:29.000000037 UTC").unwrap();assert_eq!(epoch,epoch_from_str);// Creating it from TAI will effectively show the number of leap seconds in between UTC an TAI at that epochletepoch_tai=Epoch::from_gregorian_tai(2000,2,29,14,57,29,37);// The difference between two epochs is a Durationletnum_leap_s=epoch-epoch_tai;assert_eq!(format!("{num_leap_s}"),"32 s");// Trivially convert to another time scale// Either by grabbing a subdivision of time in that time scaleassert_eq!(epoch.to_gpst_days(),7359.623402777777);// Compare to the GPS time scale// Or by fetching the exact durationletmjd_offset=Duration::from_str("51603 days 14 h 58 min 33 s 184 ms 37 ns").unwrap();assert_eq!(epoch.to_mjd_tt_duration(),mjd_offset);// Compare to the modified Julian days in the Terrestrial Time time scale.In Python:>>>fromhifitimeimport*>>>epoch=Epoch("2000-02-29T14:57:29.000000037 UTC")>>>epoch2000-02-29T14:57:29.000000037UTC>>>epoch_tai=Epoch.init_from_gregorian_tai(2000,2,29,14,57,29,37)>>>epoch_tai2000-02-29T14:57:29.000000037TAI>>>epoch.timedelta(epoch_tai)32s>>>epoch.to_gpst_days()7359.623402777777>>>epoch.to_mjd_tt_duration()51603days14h58min33s184ms37ns>>>Hifitime provides several date time formats like RFC2822, ISO8601, or RFC3339.usehifitime::efmt::consts::{ISO8601,RFC2822,RFC3339};usehifitime::prelude::*;letepoch=Epoch::from_gregorian_utc(2000,2,29,14,57,29,37);// The default Display shows the UTC time scaleassert_eq!(format!("{epoch}"),"2000-02-29T14:57:29.000000037 UTC");// Format it in RFC 2822letfmt=Formatter::new(epoch,RFC2822);assert_eq!(format!("{fmt}"),format!("Tue, 29 Feb 2000 14:57:29"));// Or in ISO8601letfmt=Formatter::new(epoch,ISO8601);assert_eq!(format!("{fmt}"),format!("2000-02-29T14:57:29.000000037 UTC"));// Which is somewhat similar to RFC3339letfmt=Formatter::new(epoch,RFC3339);assert_eq!(format!("{fmt}"),format!("2000-02-29T14:57:29.000000037+00:00"));Need some custom format? Hifitime also supports the C89 token, cf.the documentation.usecore::str::FromStr;usehifitime::prelude::*;letepoch=Epoch::from_gregorian_utc_hms(2015,2,7,11,22,33);// Parsing with a custom formatassert_eq!(Epoch::from_format_str("Sat, 07 Feb 2015 11:22:33","%a, %d %b %Y %H:%M:%S").unwrap(),epoch);// And printing with a custom formatletfmt=Format::from_str("%a, %d %b %Y %H:%M:%S").unwrap();assert_eq!(format!("{}",Formatter::new(epoch,fmt)),"Sat, 07 Feb 2015 11:22:33");You can also grab the current system time in UTC, if thestdfeature is enabled (default), and find the next or previous day of the week.usehifitime::prelude::*;#[cfg(feature ="std")]{letnow=Epoch::now().unwrap();println!("{}",now.next(Weekday::Tuesday));println!("{}",now.previous(Weekday::Sunday));}Oftentimes, we'll want to query something at a fixed step between two epochs. Hifitime makes this trivial withTimeSeries.usehifitime::prelude::*;letstart=Epoch::from_gregorian_utc_at_midnight(2017,1,14);letend=start+12.hours();letstep=2.hours();lettime_series=TimeSeries::inclusive(start,end,step);letmutcnt=0;forepochintime_series{#[cfg(feature ="std")]println!("{}",epoch);cnt+=1}// Check that there are indeed seven two-hour periods in a half a day,// including start and end times.assert_eq!(cnt,7)In Python:>>>fromhifitimeimport*>>>start=Epoch.init_from_gregorian_utc_at_midnight(2017,1,14)>>>end=start+Unit.Hour*12>>>iterator=TimeSeries(start,end,step=Unit.Hour*2,inclusive=True)>>>forepochiniterator:...print(epoch)...2017-01-14T00:00:00UTC2017-01-14T02:00:00UTC2017-01-14T04:00:00UTC2017-01-14T06:00:00UTC2017-01-14T08:00:00UTC2017-01-14T10:00:00UTC2017-01-14T12:00:00UTC>>>Durationusehifitime::prelude::*;usecore::str::FromStr;// Create a duration using the `TimeUnits` helping trait.letd=5.minutes()+7.minutes()+35.nanoseconds();assert_eq!(format!("{d}"),"12 min 35 ns");// Or using the built-in enumsletd_enum=12*Unit::Minute+35.0*Unit::Nanosecond;// But it can also be created from a stringletd_from_str=Duration::from_str("12 min 35 ns").unwrap();assert_eq!(d,d_from_str);Hifitime guarantees nanosecond precision, but most human applications don't care too much about that. Durations can be rounded to provide a useful approximation for humans.usehifitime::prelude::*;// Create a duration using the `TimeUnits` helping trait.letd=5.minutes()+7.minutes()+35.nanoseconds();// Round to the nearest minuteletrounded=d.round(1.minutes());assert_eq!(format!("{rounded}"),"12 min");// And this works on Epochs as well.letprevious_post=Epoch::from_gregorian_utc_hms(2015,2,7,11,22,33);letexample_now=Epoch::from_gregorian_utc_hms(2015,8,17,22,55,01);// We'll round to the nearest fifteen daysletthis_much_ago=example_now-previous_post;assert_eq!(format!("{this_much_ago}"),"191 days 11 h 32 min 29 s");letabout_this_much_ago_floor=this_much_ago.floor(15.days());assert_eq!(format!("{about_this_much_ago_floor}"),"180 days");letabout_this_much_ago_ceil=this_much_ago.ceil(15.days());assert_eq!(format!("{about_this_much_ago_ceil}"),"195 days");In Python:>>>fromhifitimeimport*>>>d=Duration("12 min 32 ns")>>>d.round(Unit.Minute*1)12min>>>d12min32ns>>>Comparison withtimeandchronoFirst off, bothtimeandchronoare fantastic libraries in their own right. There's a reason why they have millions and millions of downloads. Secondly, hifitime was started in October 2017, so quite a while before the revival oftime(~ 2019).One of the key differences is that bothchronoandtimeseparate the concepts of "time" and "date." Hifitime asserts that this is physically invalid: both a time and a date are an offset from a reference in a given time scale. That's why, Hifitime does not separate the components that make up a date, but instead, only stores a fixed duration with respect to TAI. Moreover, Hifitime is formally verified with a model checker, which is much more thorough than property testing.More importantly, neithertimenorchronoare suitable for astronomy, astrodynamics, or any physics that must account for time dilation due to relativistic speeds or lack of the Earth as a gravity source (which sets the "tick" of a second).Hifitime also natively supports the UT1 time scale (the only "true" time) if built with theut1feature.FeaturesInitialize a high precision Epoch from the system time in UTCLeap seconds (as announced by the IETF on a yearly basis)UTC representation with ISO8601 and RFC3339 formatting and blazing fast parsing (45 nanoseconds)Trivial support of time arithmetic: addition (e.g.2.hours() + 3.seconds()), subtraction (e.g.2.hours() - 3.seconds()), round/floor/ceil operations (e.g.2.hours().round(3.seconds()))Supports ranges of Epochs and TimeSeries (linspace ofEpochs andDurations)Trivial conversion between many time scalesHigh fidelity Ephemeris Time / Dynamic Barycentric Time (TDB) computations fromESA's NavipediaJulian dates and Modified Julian datesEmbedded device friendly:no-stdandconst fnwhere possibleThis library is validated against NASA/NAIF SPICE for the Ephemeris Time to Universal Coordinated Time computations: there are exactly zero nanoseconds of difference between SPICE and hifitime for the computation of ET and UTC after 01 January 1972. Refer to theleap secondsection for details. Other examples are validated with external references, as detailed on a test-by-test basis.Supported time scalesTemps Atomique International (TAI)Universal Coordinated Time (UTC)Terrestrial Time (TT)Ephemeris Time (ET) without the small perturbations as per NASA/NAIF SPICE leap seconds kernelDynamic Barycentric Time (TDB), a higher fidelity ephemeris timeGlobal Positioning System (GPST)Galileo System Time (GST)BeiDou Time (BDT)UNIXNon-featuresTime-agnostic / date-only epochs. Hifitime only supports the combination of date and time, but theEpoch::{at_midnight, at_noon}is provided as helper functions.DesignNo software is perfect, so please report any issue or bug onGithub.DurationUnder the hood, a Duration is represented as a 16 bit signed integer of centuries (i16) and a 64 bit unsigned integer (u64) of the nanoseconds past that century. The overflowing and underflowing of nanoseconds is handled by changing the number of centuries such that the nanoseconds number never represents more than one century (just over four centuries can be stored in 64 bits).Advantages:Exact precision of a duration: using a floating point value would cause large durations (e.g. Julian Dates) to have less precision than smaller durations. Durations in hifitime have exactly one nanosecond of precision for 65,536 years.Skipping floating point operations allows this library to be used in embedded devices without a floating point unit.Duration arithmetics are exact, e.g. one third of an hour is exactly twenty minutes and not "0.33333 hours."Disadvantages:Most astrodynamics applications require the computation of a duration in floating point values such as when querying an ephemeris. This design leads to an overhead of about 5.2 nanoseconds according to the benchmarks (Duration to f64 secondsbenchmark). You may run the benchmarks withcargo bench.EpochThe Epoch is simply a wrapper around a Duration. All epochs are stored in TAI duration with respect to 01 January 1900 at noon (the official TAI epoch). The choice of TAI meets theStandard of Fundamental Astronomy (SOFA)recommendation of opting for a glitch-free time scale (i.e. without discontinuities like leap seconds or non-uniform seconds like TDB).Printing and parsingEpochs can be formatted and parsed in the following time scales:UTC:{epoch}TAI:{epoch:x}TT:{epoch:X}TDB:{epoch:e}ET:{epoch:E}UNIX:{epoch:p}GPS:{epoch:o}Leap second supportLeap seconds allow TAI (the absolute time reference) and UTC (the civil time reference) to not drift too much. In short, UTC allows humans to see the sun at zenith at noon, whereas TAI does not worry about that. Leap seconds are introduced to allow for UTC to catch up with the absolute time reference of TAI. Specifically, UTC clocks are "stopped" for one second to make up for the accumulated difference between TAI and UTC. These leap seconds are announced several months in advance by IERS, cf. in theIETF leap second reference.The "placement" of these leap seconds in the formatting of a UTC date is left up to the software: there is no common way to handle this. Some software prevents a second tick, i.e. at 23:59:59 the UTC clock will tick fortwo seconds(instead of one) before hoping to 00:00:00. Some software, like hifitime, allow UTC dates to be formatted as 23:59:60 on strictly the days when a leap second is inserted. For example, the date2016-12-31 23:59:60 UTCis a valid date in hifitime because a leap second was inserted on 01 Jan 2017.ImportantPrior to the first leap second, NAIF SPICE claims that there were nine seconds of difference between TAI and UTC: this is different from theStandard of Fundamental Astronomy (SOFA). SOFA'siauDatfunction will return non-integer leap seconds from 1960 to 1972. It will return an error for dates prior to 1960.Hifitime only accounts for leap seconds announced byIERSin its computations: there is a ten (10) second jump between TAI and UTC on 01 January 1972. This allows the computation of UNIX time to be a specific offset of TAI in hifitime. However, the prehistoric (pre-1972) leap seconds as returned by SOFA are available in theleap_seconds()method of an epoch if theiers_onlyparameter is set to false.Ephemeris Time vs Dynamic Barycentric Time (TDB)In theory, as of January 2000, ET and TDB should now be identical.However, the NASA NAIF leap seconds files (e.g.naif00012.tls) use a simplified algorithm to compute the TDB:Equation [4], which ignores small-period fluctuations, is accurate to about 0.000030 seconds.In order to provide full interoperability with NAIF, hifitime uses the NAIF algorithm for "ephemeris time" and theESA algorithmfor "dynamical barycentric time." Hence, if exact NAIF behavior is needed, use all of the functions marked asetinstead of thetdbfunctions, such asepoch.to_et_seconds()instead ofepoch.to_tdb_seconds().Changelog3.9.0 (WIP)Update to der version 0.7.x.Introduce %y formatter by @gwbres inhttps://github.com/nyx-space/hifitime/pull/268Possible breaking change: Fix day of year computation by @ChristopherRabotin inhttps://github.com/nyx-space/hifitime/pull/2733.8.5Changes from 3.8.2 are only dependency upgrades until this release.Minimum Supported Rust version bumped from 1.64 to1.70.3.8.2Clarify README and add a section comparing Hifitime totimeandchrono, cf.#221Fix incorrect printing of Gregorian dates prior to to 1900, cf.#2043.8.1 (unreleased)Fix documentation for the formatter, cf.#202Update MSRV to 1.59 for rayon v 1.103.8.0Thanks again to@gwbresfor his work in this release!Fix CI of the formal verification and upload artifacts, cf.#179Introduce time of week construction and conversion by@gwbres, cf.#180and#188Fix minor typo insrc/timeunits.rsby@gwbres, cf.#189Significantly extend formal verification ofDurationandEpoch, and introducekani::ArbitrarytoDurationandEpochfor users to formally verify their use of time, cf.#192It is now possible to specify a Leap Seconds file (in IERS format) using theLeapSecondsFile::from_path(requires thestdfeature to read the file), cf.#43.UT1 time scale is now supported! You must build aUt1Providerstructure with data from the JPL Earth Orientation Parameters, or just useUt1Provider::download_short_from_jpl()to automatically download the data from NASA JPL.strptimeandstrftimeequivalents from C89 are now supported, cf.#181. Please refer to thedocumentationfor important limitations and how to build a custom formatter.ISO Day of Year and Day In Year are now supported for initialization of an Epoch (provided a time scale and a year), and formatting, cf.#182.Python:the representation of an epoch is now in the time scale it was initialized in3.7.0Huge thanks to@gwbreswho put in all of the work for this release. These usability changes allowRinexto use hifitime, check out this work.timescale.rs: derive serdes traits when feasible by @gwbres inhttps://github.com/nyx-space/hifitime/pull/167timecale.rs: introduce format/display by @gwbres inhttps://github.com/nyx-space/hifitime/pull/168readme: fix BeiDou typo by @gwbres inhttps://github.com/nyx-space/hifitime/pull/169epoch: derive Hash by @gwbres inhttps://github.com/nyx-space/hifitime/pull/170timescale: identify GNSS timescales from standard 3 letter codes by @gwbres inhttps://github.com/nyx-space/hifitime/pull/171timescale: standard formatting is now available by @gwbres inhttps://github.com/nyx-space/hifitime/pull/174epoch, duration: improve and fix serdes feature by @gwbres inhttps://github.com/nyx-space/hifitime/pull/175epoch, timescale: implement default trait by @gwbres inhttps://github.com/nyx-space/hifitime/pull/1763.6.0Galileo System Time and BeiDou Time are now supported, huge thanks to@gwbresfor all that work!Significant speed improvement in the initialization of Epochs from their Gregorian representation, thanks@conradludgatefor#160.Epoch and Duration now have aminandmaxfunction which respectively returns a copy of the epoch/duration that is the smallest or the largest betweenselfandother, cf.#164.[Python] Duration and Epochs now support the operators>,>=,<,<=,==, and!=. Epoch now supportsinit_from_gregorianwith a time scape, like in Rust. Epochs can also be subtracted from one another using thetimedeltafunction, cf.#162.TimeSeries can now be formatted in different time scales, cf.#1633.5.0Epoch now store the time scale that they were defined in: this allows durations to be added in their respective time scales. For example, adding 36 hours to 1971-12-31 at noon when the Epoch is initialized in UTC will lead to a different epoch than adding that same duration to an epoch initialized at the same time in TAI (because the first leap second announced by IERS was on 1972-01-01), cf. thetest_add_durations_over_leap_secondstest.RFC3339 and ISO8601 fully supported for initialization of an Epoch, including the offset, e.g.Epoch::from_str("1994-11-05T08:15:30-05:00"), cf.#73.Python package available on PyPI! To build the Python package, you must first installmaturinand then build with thepythonfeature flag. For example,maturin develop -F python && pythonwill build the Python package in debug mode and start a new shell where the package can be imported.Fix bug when printing Duration::MIN (or any duration whose centuries are minimizing the number of centuries).TimeSeries can now be formattedEpoch can now beceil-ed,floor-ed, andround-ed according to the time scale they were initialized in, cf.#145.Epoch can now be initialized from Gregorian when specifying the time system:from_gregorian,from_gregorian_hms,from_gregorian_at_noon,from_gregorian_at_midnight.Fix bug in Duration when performing operations on durations very close toDuration::MIN(i.e. minus thirty-two centuries).Duration parsing now supports multiple units in a string and does not use regular expressions. THis allows it to work withno-std.Epoch parsing no longer requiresregex.Functions are not more idiomatic: all of theas_*functions becometo_*andin_*also becomesto_*, cf.#155.3.4.0Ephemeris Time and Dynamical Barycentric Time fixed to use the J2000 reference epoch instead of the J1900 reference epoch. This is apotentially breaking changeif you relied on the previous one century error when converting from/to ET/TDB into/from UTCand storing the data as a string. There isno differenceif the original representation was used.Ephemeris Time nowstrictlymatches NAIF SPICE:the error between SPICE and hifitime is now zero nanoseconds.after the introduction of the first leap second. Prior to the first leap second, NAIF SPICE claims that there were nine seconds of difference between TAI and UTC: this is different from SOFA. Hifitime instead does not account for leap seconds in prehistoric (pre-1972) computations at all.TheStandard of Fundamentals of Astronomy(SOFA)leap seconds from 1960 to 1972 are now available with theleap_seconds() -> Option<f64>function on an instance of Epoch.Importantly, no difference in the behavior of hifitime should be noticed here: the prehistoric leap seconds are ignored in all calculations in hifitime and only provided to meet the SOFA calculations.EpochandDurationnow have the C memory representation to allow for hifitime to be embedded in C more easily.EpochandDurationcan now be encoded or decoded as ASN1 DER with theasn1dercrate feature (disabled by default).3.3.0Formal verification of the normalization operation onDuration, which in turn guarantees thatEpochoperations cannot panic, cf.#127Fixlenandsize_hintforTimeSeries, cf.#131, reported by@d3v-null, thanks for the find!Epochnow implementsEqandOrd, cf.#133, thanks@mkolopanisfor the PR!Epochcan now be printed in different time systems with format modifiers, cf.#130(minor)as_utc_durationinEpochis now public, cf.#129(minor) The whole crate now usesnum-traitsthereby skipping the explicit use oflibm. Basically, operations onf64look like normal Rust again, cf.#128(minor) Move the tests to their own folder to make it obvious that this is thoroughly tested3.2.0Fix no-std implementation by usinglibmfor non-core f64 operationsAdd UNIX timestamp, thanks@mkolopanisEnums now deriveEqand some deriveOrd(where relevant)#118Use const fn where possible and switch to references where possible#119Allow extracting the centuries and nanoseconds of aDurationandEpoch, respectively with to_parts and to_tai_parts#122Addceil,floor,roundoperations toEpochandDuration3.1.0Add#![no_std]supportAddto_partstoDurationto extract the centuries and nanoseconds of a durationAllow building anEpochfrom its duration and parts in TAI systemAdd pure nanosecond (u64) constructor and getter for GPST since GPS based clocks will count in nanosecondsPossibly breaking changeErrors::ParseErrorno longer contains aStringbut an enumParsingErrorsinstead. This is considered possibly breaking because it would only break code in the cases where a datetime parsing or unit parsing was caught and handled (uncommon). Moreover, the output is stillDisplay-able.3.0.0Backend rewritten from TwoFloat to a struct of the centuries ini16and nanoseconds inu64. Thanks to@pwnorbitalsfor proposing the idea in #107and writing the proof of concept. This leads to at least a 2x speed up in most calculations, cf.this comment.Fix GPS epoch, and addition of a helper functions inEpochby@cjordanImportant Update on Versioning StrategyWe want to inform our users of an important change in Hifitime's versioning approach. Starting with version 3.9.0, minor version updates may include changes that could potentially break backward compatibility. While we strive to maintain stability and minimize disruptions, this change allows us to incorporate significant improvements and adapt more swiftly to evolving user needs. We recommend users to carefully review the release notes for each update, even minor ones, to understand any potential impacts on their existing implementations. Our commitment to providing a robust and dynamic time management library remains steadfast, and we believe this change in versioning will better serve the evolving demands of our community.