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   u128

duration_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 UTC

DateTime::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

  • SystemTime is not monotonic. The system clock can be adjusted backwards. Measure elapsed time with Instant, and keep SystemTime for wall-clock timestamps.
  • Unsigned results. as_secs() is a u64 and as_millis() a u128; most databases and JSON APIs want an i64. Convert with i64::try_from rather than as, 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.
  • NaiveDateTime in 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.