在Rust中将Unix时间戳转换为可读的时间字符串?
如何将Unix时间戳在Rust中将Unix时间戳转换为可读的时间字符串?,rust,Rust,如何将Unix时间戳1524820690转换为可读的日期时间字符串 就像Python中的这样: [1]中的:从日期时间导入日期时间 在[2]中:打印( …:datetime.fromtimestamp(1284101485).strftime(“%Y-%m-%d%H:%m:%S”) ...: ) 2010-09-10 14:51:25 我不熟悉Rust,但您应该能够将Unix时间戳转换为整数(i64),然后使用NaiveDateTimefromchrono将时间戳转换为格式化字符串 这里有一个例
1524820690
转换为可读的日期时间字符串
就像Python中的这样:
[1]中的:从日期时间导入日期时间
在[2]中:打印(
…:datetime.fromtimestamp(1284101485).strftime(“%Y-%m-%d%H:%m:%S”)
...: )
2010-09-10 14:51:25
我不熟悉Rust,但您应该能够将Unix时间戳转换为整数(i64),然后使用NaiveDateTime
fromchrono
将时间戳转换为格式化字符串
这里有一个例子
extern板条箱计时;
使用chrono::前奏::*;
fn main(){
//将时间戳字符串转换为i64
让timestamp=“1524820690.parse::().unwrap();
//从时间戳创建一个DateTime
让naive=NaiveDateTime::from_timestamp(timestamp,0);
//从NaiveDateTime创建普通DateTime
让datetime:datetime=datetime::from_utc(朴素,utc);
//按所需格式设置日期时间
让newdate=datetime.format(“%Y-%m-%d%H:%m:%S”);
//打印新格式化的日期和时间
println!(“{}”,newdate);
}
我使用了你的Python时间格式,但格式可能与Rust不同。谢谢@coffeed up hacker的回答。这对我帮助很大 我尝试了许多不同的方法来实现这一点,但似乎内置函数无法将SystemTime格式化为可读的时间字符串 最后,我找到了一个更好的方法,它适用于各种情况:
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};
}
要获取本地时间字符串,只需使用以下命令:DateTime:::from(d)
此外,我们可以使用
Duration::from_millis
或Duration::from_micros
或Duration::from_nanos
将毫秒、微秒、纳秒转换为可读字符串。Hi,@shepmaster,我认为这两个问题并不相似。从重复的标记可以看出,我是这样做的。您是否愿意进一步说明为什么您认为它们是不同的?两者似乎都只是简单地使用NaiveDateTime
.1。我想将unix timestamp:i64转换为可读字符串,问题是要转换为chrono::prelude::Datetime
。2.这个问题有一个标签rust-chrono
,我希望内置函数可以做到这一点,而不仅仅是chrono
@coffeed up hacker的答案使用了NaiveDateTime
来做这个把戏,但我得到了一个更简单、更一般的答案,这不是关于使用NaiveDateTime
。另外请注意,重复项没有什么错。这个问题现在为任何人提供了一个路标,他们使用了你在发布这个问题之前使用的相同搜索词,让他们找到正确的答案。我希望内置函数可以做到这一点-你从未在问题中声明过这样的限制,事实上,双方都接受了答案,并提供了自己的使用chrono的答案。我得到了一个更简单、更一般的答案,它不是关于使用NaiveDateTime的——重复的答案也会创建一个DateTime
。如果您认为您的解决方案是一种更好的方法,建议您将答案移至副本。我无法使用“类型注释”日期时间编译上述内容:::from_utc(utc_DateTime,utc);
2018-04-28 03:15:22.000000000