5

How does one convert a u64 unix timestamp into a DateTime<Utc>?

let timestamp_u64 = 1657113606;
let date_time = ...
alextes
  • 1,817
  • 2
  • 15
  • 22

1 Answers1

6

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_opt we can use.

use chrono::{TimeZone, Utc};
    
let timestamp_u64 = 1657113606;
let date_time = Utc.timestamp_opt(timestamp_u64 as i64, 0).unwrap();

playground

alextes
  • 1,817
  • 2
  • 15
  • 22
  • 1
    the answer only solves for i64 -> DateTime, not u64 like the question asked. An important nuance, since with u64 you have to account for extra precision. – pdeuchler Apr 15 '23 at 23:19
  • You can either `as i64` or `.try_into().unwrap()` which is safe for unix timestamps unless you're working with timestamps billions of years into the future. I'll edit the answer to be for u64. – alextes Aug 12 '23 at 08:05