Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unix timestamp to readable time string in Rust? [duplicate]

Tags:

rust

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
like image 590
McGrady Avatar asked Apr 28 '18 01:04

McGrady


People also ask

How do you get a Unix timestamp in Rust?

Rust current time in Milliseconds SystemTime::now() returns SystemTime object that contains current time . duration_since returns the Duration of difference between current time and Unix Time. as_millis function return the total number of millisecond. Below program get the current time.

How do I convert timestamp to epoch?

Convert from human-readable date to epoch long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

What is Unix timestamp string?

The Unix timestamp is the number of seconds calculated since January 1, 1970.


2 Answers

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.

like image 125
Coffee'd Up Hacker Avatar answered Oct 07 '22 21:10

Coffee'd Up Hacker


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.

like image 43
McGrady Avatar answered Oct 07 '22 22:10

McGrady