【问题标题】:Converting Unix timestamp to readable time string in Rust? [duplicate]将 Unix 时间戳转换为 Rust 中的可读时间字符串? [复制]
【发布时间】:2018-10-08 20:51:28
【问题描述】:

如何将 Unix 时间戳 1524820690 转换为可读的日期时间字符串?

在 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,我认为这两个问题并不相似。
  • 从重复标记可以看出,我知道。您愿意详细说明您认为它们不同的原因吗?两者似乎都只是使用NaiveDateTime
  • 1.我想将 unix timestamp:i64 转换为可读字符串,问题即将转换为chrono:: prelude ::Datetime。 2. 这个问题有一个标签rust-chrono,我希望内置函数可以做到这一点,而不仅仅是chrono.3。 @coffee-up-hacker 的答案使用 NaiveDateTime 来实现这个技巧,但我得到了一个更简单、更通用的答案,这与使用 NaiveDateTime 无关。
  • 另请注意,重复项没有错。现在,此问题为使用您发布此问题之前使用的相同搜索字词的任何人提供了一个路标,让他们得到正确的答案。
  • 我希望内置函数可以做到这一点——您从未在问题中声明过这样的限制,并且确实都接受了答案并提供了您自己的使用 chrono。 我得到了一个更简单、更通用的答案,它与使用 NaiveDateTime 无关 — 重复的答案也创建了一个 DateTime。如果您认为您的解决方案是一种更好的方法,我们鼓励您将答案移至副本。

标签: rust


【解决方案1】:

我不熟悉 Rust,但您应该能够将 Unix 时间戳转换为整数 (i64),然后使用 NaiveDateTime from chrono 将时间戳转换为格式化字符串。

这是一个例子......

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);
}

我使用了你的 Python 时间格式,但 Rust 中的格式可能不同。

【讨论】:

  • 我无法使用“类型注释” DateTime::::from_utc(utc_datetime, Utc);
【解决方案2】:

感谢@coffee-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};
}

输出:

2018-04-28 03:15:22.000000000

要获取本地时间字符串,只需使用:DateTime::&lt;Local&gt;::from(d)

另外,我们可以使用Duration::from_millisDuration::from_microsDuration::from_nanos 将毫秒、微秒、纳秒转换为可读字符串。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2017-01-18
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多