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
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.
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.
The Unix timestamp is the number of seconds calculated since January 1, 1970.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With