【问题标题】:handling unix timestaps in rust with chrono使用 chrono 处理 rust 中的 unix 时间戳
【发布时间】:2021-07-24 23:25:01
【问题描述】:

我似乎无法弄清楚如何使用 chrono 在 Rust 中处理 Unix 时间戳。

我有以下代码,但是 naivedatetime 变量不正确:

use chrono::{Utc, DateTime, NaiveDateTime};

fn main() {
    println!("Hello, world!");

    let timestamp = "1627127393230".parse::<i64>().unwrap();
    let naive = NaiveDateTime::from_timestamp(timestamp, 0);
    let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);

    println!("timestamp: {}", timestamp);
    println!("naive: {}", naive);
    println!("datetime: {}", datetime);
}

输出:

❯ cargo r
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/utc`
Hello, world!
timestamp: 1627127393230
naive: +53531-08-13 23:27:10
datetime: +53531-08-13 23:27:10 UTC

1627127393230 的正确日期时间为:

GMT: Saturday, July 24, 2021 11:49:53.230 AM

谁能告诉我我在这里缺少什么。 谢谢

编辑:

最终解决方案:

use chrono::{DateTime, Utc, NaiveDateTime};

pub fn convert(timestamp: i64)  -> DateTime<Utc> {
    let naive = NaiveDateTime::from_timestamp_opt(timestamp / 1000, (timestamp % 1000) as u32 * 1_000_000).unwrap();
    DateTime::<Utc>::from_utc(naive, Utc)
}


#[test]
fn test_timestamp() {
    let timestamp = 1627127393230;
    let ts = convert(timestamp);
    assert_eq!(ts.to_string(), "2021-07-24 11:49:53.230 UTC")
}

【问题讨论】:

    标签: rust chrono


    【解决方案1】:

    from_timestamp 不支持毫秒。 您可以将毫秒放在第二个参数中作为纳秒。但是你必须把它从时间戳中取出来。

    查看子字符串 crate 或这样做:

    use chrono::{DateTime, NaiveDateTime, Utc}; 
    
    fn main() {
        let timestamp = 1627127393i64;
        let nanoseconds = 230 * 1000000;
        let datetime = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, nanoseconds), Utc);
        println!("{}", datetime);
    }
    

    使用子字符串 crate:

    use substring::Substring;
    use chrono::{DateTime, NaiveDateTime, Utc}; 
    
    fn main() {
        let timestamp = "1627127393230";
        let nanoseconds = substring(timestamp, 11, 3).parse::<i64>().unwrap() * 1000000;
        let timestamp = substring(timestamp, 1, 10).parse::<i64>().unwrap();
        let datetime = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, nanoseconds), Utc);
        println!("{}", datetime);
    }
    

    【讨论】:

    • 有没有办法在 chrono 中处理毫秒?
    • from_timstamp 的第二个参数需要纳秒,只是相应地改变大小:-)
    【解决方案2】:

    您的timestamp 输入是

    1627127393230

    current Unix timestamp

    1627169482

    请注意,您的timestamp 相差了三个数量级,但小数点似乎是正确的。所以我的猜测是你的输入——无论你从哪里获得值——在其表示中包括纳秒精度。

    如果您知道这是真的,请使用timestamp / 1000 和/或将余数改组到from_timestamp 的第二个参数中。

    【讨论】:

    • 哈,呵呵。这就对了。感谢您发现这一点。
    • 请接受答案,以便将其标记为已关闭。
    猜你喜欢
    • 2022-07-06
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2017-06-02
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多