Unix timestamps in Rust
The standard library can give you the timestamp but knows nothing about calendars. For dates, time zones and formatting you need a crate; chrono is the usual choice.
Current timestamp (standard library)
use std::time::{SystemTime, UNIX_EPOCH};
let since_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock is set before 1970");
println!("{}", since_epoch.as_secs()); // e.g. 1763164800 u64
println!("{}", since_epoch.as_millis()); // e.g. 1763164800123 u128duration_since returns a Result because a Duration cannot be negative: if the clock is set before 1970 you get an error rather than a negative number.
Timestamp to date (chrono)
Every example uses 1700000000, which is 14 November 2023 at 22:13:20 UTC, so you can compare the output across languages or check it in the timestamp converter.
use chrono::{DateTime, Utc};
let dt: DateTime<Utc> = DateTime::from_timestamp(1_700_000_000, 0).expect("in range");
println!("{}", dt.to_rfc3339()); // 2023-11-14T22:13:20+00:00
println!("{}", dt.format("%Y-%m-%d %H:%M:%S")); // 2023-11-14 22:13:20
let ms = DateTime::from_timestamp_millis(1_700_000_000_123).expect("in range");
println!("{}", ms); // 2023-11-14 22:13:20.123 UTCDateTime::from_timestamp exists from chrono 0.4.31. It returns an Option, which is None when the value is out of range. Named zones such as America/New_York come from the separate chrono-tz crate.
Date to timestamp (chrono)
use chrono::{DateTime, TimeZone, Utc};
let parsed = DateTime::parse_from_rfc3339("2023-11-14T22:13:20Z").expect("valid RFC 3339");
println!("{}", parsed.timestamp()); // 1700000000
println!("{}", parsed.timestamp_millis()); // 1700000000000
let built = Utc.with_ymd_and_hms(2023, 11, 14, 22, 13, 20).unwrap();
println!("{}", built.timestamp()); // 1700000000
Pitfalls
SystemTimeis not monotonic. The system clock can be adjusted backwards. Measure elapsed time withInstant, and keepSystemTimefor wall-clock timestamps.- Unsigned results.
as_secs()is au64andas_millis()au128; most databases and JSON APIs want ani64. Convert withi64::try_fromrather thanas, which would truncate silently. - Without a crate you can still go from a timestamp to a
SystemTime:UNIX_EPOCH + Duration::from_secs(1_700_000_000). You cannot print it as a date. NaiveDateTimein chrono has no zone. Call.and_utc()before.timestamp(), so the conversion states which zone you mean.
Questions
How do I get the current Unix timestamp in Rust?
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() with std::time. With chrono, Utc::now().timestamp().
Can Rust format a timestamp as a date without a crate?
No. The standard library has SystemTime and Duration but no calendar or formatting. Use chrono, time or jiff.