Chrono DateTime from u64 unix timestamp in Rust

120

Question: Chrono DateTime from u64 unix timestamp in Rust

How does one convert a u64 or string into a DateTime<Utc>?

let timestamp_u64 = 1657113606; let date_time = ... 

Total Answers: 1

95

Answers 1: of Chrono DateTime from u64 unix timestamp in Rust

There are many options.

Assuming we want a chrono::DateTime. The offset page suggests:

Using the TimeZone methods on the UTC struct is the preferred way to construct DateTime instances.

There is a TimeZone method timestamp we can use.

use chrono::{DateTime, TimeZone, Utc};  let timestamp_u64 = 1657113606; let date_time = Utc.timestamp(timestamp_u64, 0); 

Another option uses the appropriately named from_timestamp method, but needs more code to do it.

use chrono::{DateTime, NaiveDateTime, Utc};  let timestamp_u64 = 1657113606; let naive_date_time = NaiveDateTime::from_timestamp(timestamp_u64, 0); let date_time = DateTime::<Utc>::from_utc(naive_date_time, Utc);