26

How can I convert the Unix timestamp 1524820690 to a readable date time string?

Just like this in Python:

In [1]: from datetime import datetime
In [2]: print(
   ...:     datetime.fromtimestamp(1284101485).strftime('%Y-%m-%d %H:%M:%S')
   ...: )
2010-09-10 14:51:25
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • Hi, @shepmaster, I don't think the two questions are similar. – McGrady Apr 29 '18 at 01:40
  • As you can tell by the duplicate marking, I do. Would you care to expand on why you think they *are* different? Both appear to simply be about using `NaiveDateTime`. – Shepmaster Apr 29 '18 at 02:00
  • 1. I want to convert unix timestamp:i64 to readable string, the question is about to convert to `chrono:: prelude ::Datetime`. 2. There's a tag `rust-chrono` for that question and I hope built-in functions can do this, not just `chrono`.3. @coffeed-up-hacker's answer uses `NaiveDateTime ` to do this trick, but I got a simpler and more general answer which is not about using `NaiveDateTime`. – McGrady Apr 29 '18 at 02:08
  • Also note that there's *nothing wrong* with duplicates. This question now provides a signpost to anyone who used the same search terms you used before posting this question, getting them to the right answer. – Shepmaster Apr 29 '18 at 02:09
  • *I hope built-in functions can do this* — you never stated such a restriction in the question and indeed both accepted an answer and provided your own that use chrono. *I got a simpler and more general answer which is not about using NaiveDateTime* — the duplicate's answer creates a `DateTime` as well. If you think your solution is a better method, you are encouraged to move your answer to the duplicate. – Shepmaster Apr 29 '18 at 02:14
  • @McGrady 1. this is pretty must 99% of the job, in rust it's very easy to convert a result to string 2. Rust standard library avoid to be big, chrono is design to do this job, there is no reason to not use it 3. use `NaiveDateTime` is perfectly correct for timestamp. I agree this question is answered perfectly in the duplicate. – Stargateur Apr 29 '18 at 02:28

2 Answers2

29

I am not familiar with Rust, but you should be able to convert the Unix timestamp to an integer (i64), and than use NaiveDateTime from chrono to convert the timestamp into a formatted string.

Here's an example...

extern crate chrono;

use chrono::prelude::*;

fn main() {
    // Convert the timestamp string into an i64
    let timestamp = "1524820690".parse::<i64>().unwrap();
    
    // Create a NaiveDateTime from the timestamp
    let naive = NaiveDateTime::from_timestamp(timestamp, 0);
    
    // Create a normal DateTime from the NaiveDateTime
    let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);
    
    // Format the datetime how you want
    let newdate = datetime.format("%Y-%m-%d %H:%M:%S");

    // Print the newly formatted date and time
    println!("{}", newdate);
}

I used your Python time format, but the formatting might be different in Rust.

carols10cents
  • 6,943
  • 7
  • 39
  • 56
Coffee'd Up Hacker
  • 1,356
  • 11
  • 23
17

Thanks for @coffeed-up-hacker's answer.It helps me a lot.

I tried many different ways to do this, and it seems that built-in functions can not format SystemTime to readable time string.

Finally, I found a better way and it applies to a variety of situations:

extern crate chrono;
use chrono::prelude::DateTime;
use chrono::Utc;
use std::time::{SystemTime, UNIX_EPOCH, Duration};


fn main(){
    // Creates a new SystemTime from the specified number of whole seconds
    let d = UNIX_EPOCH + Duration::from_secs(1524885322);
    // Create DateTime from SystemTime
    let datetime = DateTime::<Utc>::from(d);
    // Formats the combined date and time with the specified format string.
    let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S.%f").to_string();
    println!{"{}",timestamp_str};
}

Output:

2018-04-28 03:15:22.000000000

To get local time string, just use this :DateTime::<Local>::from(d).

Also, we can use Duration::from_millis or Duration::from_micros or Duration::from_nanos to convert millisecond, microsecond, nanoseconds to readable string.

vallentin
  • 23,478
  • 6
  • 59
  • 81
McGrady
  • 10,869
  • 13
  • 47
  • 69