How to initialize std::time::SysemTime to an arbitrary value

There seem to be plenty of discussions available on how to convert from SysTime to DateTime, for example ( Systime To DateTime ) but not the other way around.

In fact it seems as though the only way to initialize a SystemTime is using the now() method. How does one declare an arbitrary SystemTime? For example, the time of the first moon walk!

The reason I wish to do this, is that I have postgres code that works great for binding System values. I can read them all day, and write them between data columns all day, but I cannot create any new values other than from file timestamps, or the now() method.

You could do SystemTime::UNIX_EPOCH + Duration::from_secs(arbitrary_unix_timestamp), although this feels like an hack.

1 Like

If it works, it works. How would you go about creating the arbitrary_unix_timestamp?

You can convert from types created by the time or chrono crates:

Thank you. With your suggestion I wrote the following code and it seems to work. I'm not exactly sure how to make sense of the doc links you sent, entirely. I need to get better at reading the docs.

Any how this code works and performs successful conversions between from Datetime to SystemTime.

use chrono::{DateTime, Utc};
use std::time::SystemTime;

fn main() {
    let system_time = SystemTime::now();
    let datetime: DateTime<Utc> = system_time.into();
    println!("Current now() from SystemTime= {}", datetime.format("%m/%d/%Y %T"));

    // take round trip from an arbitrary datetime to systemtime and back.
    let datetime = DateTime::parse_from_rfc3339("1996-12-19T16:39:57-00:00").unwrap();
    println!("Arbitrary Datetime = {}", datetime.format("%m/%d/%Y %T"));

    let back_to_systime: SystemTime = SystemTime::from(datetime);
    let back_to_datetime: DateTime<Utc> = back_to_systime.into();
    println!("back_to_datetime from systemtime = {}",
        back_to_datetime.format("%m/%d/%Y %T"));


Here's the output I get running it today:

Current now() from SystemTime= 01/16/2022 20:33:24
Arbitrary Datetime = 12/19/1996 16:39:57
back_to_datetime from systemtime = 12/19/1996 16:39:57

One thing worth mentioning, is that I have found it easier to bind SystemTime to postgres pg date time stamps using just the native drivers. I was running into more issues binding to DateTime.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.