pub struct SystemTime(/* private fields */);
std
only.Expand description
A measurement of the system clock, useful for talking to external entities like the file system or other processes.
Distinct from the Instant
type, this time measurement is not
monotonic. This means that you can save a file to the file system, then
save another file to the file system, and the second file has a
SystemTime
measurement earlier than the first. In other words, an
operation that happens after another operation in real time may have an
earlier SystemTime
!
Consequently, comparing two SystemTime
instances to learn about the
duration between them returns a Result
instead of an infallible Duration
to indicate that this sort of time drift may happen and needs to be handled.
Although a SystemTime
cannot be directly inspected, the UNIX_EPOCH
constant is provided in this module as an anchor in time to learn
information about a SystemTime
. By calculating the duration from this
fixed point in time, a SystemTime
can be converted to a human-readable time,
or perhaps some other string representation.
The size of a SystemTime
struct may vary depending on the target operating
system.
A SystemTime
does not count leap seconds.
SystemTime::now()
’s behavior around a leap second
is the same as the operating system’s wall clock.
The precise behavior near a leap second
(e.g. whether the clock appears to run slow or fast, or stop, or jump)
depends on platform and configuration,
so should not be relied on.
Example:
use std::time::{Duration, SystemTime};
use std::thread::sleep;
fn main() {
let now = SystemTime::now();
// we sleep for 2 seconds
sleep(Duration::new(2, 0));
match now.elapsed() {
Ok(elapsed) => {
// it prints '2'
println!("{}", elapsed.as_secs());
}
Err(e) => {
// an error occurred!
println!("Error: {e:?}");
}
}
}
§Platform-specific behavior
The precision of SystemTime
can depend on the underlying OS-specific time format.
For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
can represent nanosecond intervals.
The following system calls are currently being used by now()
to find out
the current time:
Platform | System call |
---|---|
SGX | insecure_time usercall. More information on timekeeping in SGX |
UNIX | clock_gettime (Realtime Clock) |
Darwin | clock_gettime (Realtime Clock) |
VXWorks | clock_gettime (Realtime Clock) |
SOLID | SOLID_RTC_ReadTime |
WASI | __wasi_clock_time_get (Realtime Clock) |
Windows | GetSystemTimePreciseAsFileTime / GetSystemTimeAsFileTime |
Disclaimer: These system calls might change over time.
Note: mathematical operations like
add
may panic if the underlying structure cannot represent the new point in time.
Implementations§
Source§impl SystemTime
impl SystemTime
1.28.0 · Sourcepub const UNIX_EPOCH: SystemTime = UNIX_EPOCH
pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH
An anchor in time which can be used to create new SystemTime
instances or
learn about where in time a SystemTime
lies.
This constant is defined to be “1970-01-01 00:00:00 UTC” on all systems with
respect to the system clock. Using duration_since
on an existing
SystemTime
instance can tell how far away from this point in time a
measurement lies, and using UNIX_EPOCH + duration
can be used to create a
SystemTime
instance to represent another fixed point in time.
duration_since(UNIX_EPOCH).unwrap().as_secs()
returns
the number of non-leap seconds since the start of 1970 UTC.
This is a POSIX time_t
(as a u64
),
and is the same time representation as used in many Internet protocols.
§Examples
use std::time::SystemTime;
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
1.8.0 · Sourcepub fn now() -> SystemTime
pub fn now() -> SystemTime
Returns the system time corresponding to “now”.
§Examples
use std::time::SystemTime;
let sys_time = SystemTime::now();
1.8.0 · Sourcepub fn duration_since(
&self,
earlier: SystemTime,
) -> Result<Duration, SystemTimeError> ⓘ
pub fn duration_since( &self, earlier: SystemTime, ) -> Result<Duration, SystemTimeError> ⓘ
Returns the amount of time elapsed from an earlier point in time.
This function may fail because measurements taken earlier are not
guaranteed to always be before later measurements (due to anomalies such
as the system clock being adjusted either forwards or backwards).
Instant
can be used to measure elapsed time without this risk of failure.
If successful, Ok(Duration)
is returned where the duration represents
the amount of time elapsed from the specified measurement to this one.
Returns an Err
if earlier
is later than self
, and the error
contains how far from self
the time is.
§Examples
use std::time::SystemTime;
let sys_time = SystemTime::now();
let new_sys_time = SystemTime::now();
let difference = new_sys_time.duration_since(sys_time)
.expect("Clock may have gone backwards");
println!("{difference:?}");
1.8.0 · Sourcepub fn elapsed(&self) -> Result<Duration, SystemTimeError> ⓘ
pub fn elapsed(&self) -> Result<Duration, SystemTimeError> ⓘ
Returns the difference from this system time to the current clock time.
This function may fail as the underlying system clock is susceptible to
drift and updates (e.g., the system clock could go backwards), so this
function might not always succeed. If successful, Ok(Duration)
is
returned where the duration represents the amount of time elapsed from
this time measurement to the current time.
To measure elapsed time reliably, use Instant
instead.
Returns an Err
if self
is later than the current system time, and
the error contains how far from the current system time self
is.
§Examples
use std::thread::sleep;
use std::time::{Duration, SystemTime};
let sys_time = SystemTime::now();
let one_sec = Duration::from_secs(1);
sleep(one_sec);
assert!(sys_time.elapsed().unwrap() >= one_sec);
1.34.0 · Sourcepub fn checked_add(&self, duration: Duration) -> Option<SystemTime> ⓘ
pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> ⓘ
Returns Some(t)
where t
is the time self + duration
if t
can be represented as
SystemTime
(which means it’s inside the bounds of the underlying data structure), None
otherwise.
1.34.0 · Sourcepub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> ⓘ
pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> ⓘ
Returns Some(t)
where t
is the time self - duration
if t
can be represented as
SystemTime
(which means it’s inside the bounds of the underlying data structure), None
otherwise.
Trait Implementations§
1.8.0 · Source§impl Add<Duration> for SystemTime
impl Add<Duration> for SystemTime
Source§fn add(self, dur: Duration) -> SystemTime
fn add(self, dur: Duration) -> SystemTime
§Panics
This function may panic if the resulting point in time cannot be represented by the
underlying data structure. See SystemTime::checked_add
for a version without panic.
Source§type Output = SystemTime
type Output = SystemTime
+
operator.1.9.0 · Source§impl AddAssign<Duration> for SystemTime
impl AddAssign<Duration> for SystemTime
Source§fn add_assign(&mut self, other: Duration)
fn add_assign(&mut self, other: Duration)
+=
operation. Read more§impl ArchiveWith<SystemTime> for AsUnixTime
impl ArchiveWith<SystemTime> for AsUnixTime
§type Archived = ArchivedDuration
type Archived = ArchivedDuration
Self
with F
.§fn resolve_with(
field: &SystemTime,
resolver: <AsUnixTime as ArchiveWith<SystemTime>>::Resolver,
out: Place<<AsUnixTime as ArchiveWith<SystemTime>>::Archived>,
)
fn resolve_with( field: &SystemTime, resolver: <AsUnixTime as ArchiveWith<SystemTime>>::Resolver, out: Place<<AsUnixTime as ArchiveWith<SystemTime>>::Archived>, )
F
.Source§impl BitSized<128> for SystemTime
impl BitSized<128> for SystemTime
Source§const BIT_SIZE: usize = _
const BIT_SIZE: usize = _
Source§const MIN_BYTE_SIZE: usize = _
const MIN_BYTE_SIZE: usize = _
1.8.0 · Source§impl Clone for SystemTime
impl Clone for SystemTime
Source§fn clone(&self) -> SystemTime
fn clone(&self) -> SystemTime
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more1.8.0 · Source§impl Debug for SystemTime
impl Debug for SystemTime
Source§impl<'de> Deserialize<'de> for SystemTime
impl<'de> Deserialize<'de> for SystemTime
Source§fn deserialize<D>(
deserializer: D,
) -> Result<SystemTime, <D as Deserializer<'de>>::Error> ⓘwhere
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<SystemTime, <D as Deserializer<'de>>::Error> ⓘwhere
D: Deserializer<'de>,
§impl<D> DeserializeWith<ArchivedDuration, SystemTime, D> for AsUnixTime
impl<D> DeserializeWith<ArchivedDuration, SystemTime, D> for AsUnixTime
§fn deserialize_with(
field: &ArchivedDuration,
_: &mut D,
) -> Result<SystemTime, <D as Fallible>::Error> ⓘ
fn deserialize_with( field: &ArchivedDuration, _: &mut D, ) -> Result<SystemTime, <D as Fallible>::Error> ⓘ
F
using the given deserializer.§impl From<Timestamp> for SystemTime
impl From<Timestamp> for SystemTime
§fn from(time: Timestamp) -> SystemTime
fn from(time: Timestamp) -> SystemTime
§impl From<Zoned> for SystemTime
impl From<Zoned> for SystemTime
§fn from(time: Zoned) -> SystemTime
fn from(time: Zoned) -> SystemTime
§impl FromPyObject<'_> for SystemTime
impl FromPyObject<'_> for SystemTime
§fn extract_bound(obj: &Bound<'_, PyAny>) -> Result<SystemTime, PyErr> ⓘ
fn extract_bound(obj: &Bound<'_, PyAny>) -> Result<SystemTime, PyErr> ⓘ
1.8.0 · Source§impl Hash for SystemTime
impl Hash for SystemTime
§impl IntoPy<Py<PyAny>> for SystemTime
impl IntoPy<Py<PyAny>> for SystemTime
§impl<'py> IntoPyObject<'py> for &SystemTime
impl<'py> IntoPyObject<'py> for &SystemTime
§type Output = Bound<'py, <&SystemTime as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <&SystemTime as IntoPyObject<'py>>::Target>
§fn into_pyobject(
self,
py: Python<'py>,
) -> Result<<&SystemTime as IntoPyObject<'py>>::Output, <&SystemTime as IntoPyObject<'py>>::Error> ⓘ
fn into_pyobject( self, py: Python<'py>, ) -> Result<<&SystemTime as IntoPyObject<'py>>::Output, <&SystemTime as IntoPyObject<'py>>::Error> ⓘ
§impl<'py> IntoPyObject<'py> for SystemTime
impl<'py> IntoPyObject<'py> for SystemTime
§type Output = Bound<'py, <SystemTime as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <SystemTime as IntoPyObject<'py>>::Target>
§fn into_pyobject(
self,
py: Python<'py>,
) -> Result<<SystemTime as IntoPyObject<'py>>::Output, <SystemTime as IntoPyObject<'py>>::Error> ⓘ
fn into_pyobject( self, py: Python<'py>, ) -> Result<<SystemTime as IntoPyObject<'py>>::Output, <SystemTime as IntoPyObject<'py>>::Error> ⓘ
1.8.0 · Source§impl Ord for SystemTime
impl Ord for SystemTime
Source§fn cmp(&self, other: &SystemTime) -> Ordering
fn cmp(&self, other: &SystemTime) -> Ordering
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
1.8.0 · Source§impl PartialEq for SystemTime
impl PartialEq for SystemTime
1.8.0 · Source§impl PartialOrd for SystemTime
impl PartialOrd for SystemTime
Source§impl Serialize for SystemTime
impl Serialize for SystemTime
Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> ⓘwhere
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> ⓘwhere
S: Serializer,
§impl<S> SerializeWith<SystemTime, S> for AsUnixTime
impl<S> SerializeWith<SystemTime, S> for AsUnixTime
§fn serialize_with(
field: &SystemTime,
_: &mut S,
) -> Result<<AsUnixTime as ArchiveWith<SystemTime>>::Resolver, <S as Fallible>::Error> ⓘ
fn serialize_with( field: &SystemTime, _: &mut S, ) -> Result<<AsUnixTime as ArchiveWith<SystemTime>>::Resolver, <S as Fallible>::Error> ⓘ
F
using the given serializer.1.8.0 · Source§impl Sub<Duration> for SystemTime
impl Sub<Duration> for SystemTime
Source§type Output = SystemTime
type Output = SystemTime
-
operator.1.9.0 · Source§impl SubAssign<Duration> for SystemTime
impl SubAssign<Duration> for SystemTime
Source§fn sub_assign(&mut self, other: Duration)
fn sub_assign(&mut self, other: Duration)
-=
operation. Read more§impl ToPyObject for SystemTime
impl ToPyObject for SystemTime
§impl TryFrom<SystemTime> for Timestamp
impl TryFrom<SystemTime> for Timestamp
Source§impl TryFrom<SystemTime> for UnixTimeI64
impl TryFrom<SystemTime> for UnixTimeI64
§impl TryFrom<SystemTime> for Zoned
impl TryFrom<SystemTime> for Zoned
impl Copy for SystemTime
impl Eq for SystemTime
impl StructuralPartialEq for SystemTime
Auto Trait Implementations§
impl Freeze for SystemTime
impl RefUnwindSafe for SystemTime
impl Send for SystemTime
impl Sync for SystemTime
impl Unpin for SystemTime
impl UnwindSafe for SystemTime
Blanket Implementations§
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
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> ByteSized for T
impl<T> ByteSized for T
Source§const BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Source§fn byte_align(&self) -> usize ⓘ
fn byte_align(&self) -> usize ⓘ
Source§fn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Source§impl<T, R> Chain<R> for Twhere
T: ?Sized,
impl<T, R> Chain<R> for Twhere
T: ?Sized,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.Source§impl<T> ExtAny for T
impl<T> ExtAny for T
Source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Source§impl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
Source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Source§fn mem_align_of_val(&self) -> usize ⓘ
fn mem_align_of_val(&self) -> usize ⓘ
Source§fn mem_size_of_val(&self) -> usize ⓘ
fn mem_size_of_val(&self) -> usize ⓘ
Source§fn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true
if dropping values of this type matters. Read moreSource§fn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self
without running its destructor. Read moreSource§fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Source§unsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice
only.§impl<'py, T> FromPyObjectBound<'_, 'py> for Twhere
T: FromPyObject<'py>,
impl<'py, T> FromPyObjectBound<'_, 'py> for Twhere
T: FromPyObject<'py>,
§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Hook for T
impl<T> Hook for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more§impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
§fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
self
into an owned Python object, dropping type information.§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> ⓘ
§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out
indicating that a T
is niched.