rust - 使用 chrono 处理 rust 中的 unix 时间戳

标签 rust chrono

我似乎无法弄清楚如何使用 chrono 在 Rust 中处理 Unix 时间戳.
我有以下代码,但是 naive因此 datetime变量不正确:

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

最佳答案

您的 timestamp输入是
1627127393230
current Unix timestamp
1627169482
请注意您的 timestamp相差三个数量级,但小数似乎是正确的。所以我的猜测是你的输入——无论你从哪里得到值——在它的表示中包括纳秒精度。
如果您知道这是真的,请使用 timestamp / 1000和/或将余数洗牌到第二个参数中 from_timestamp .

关于rust - 使用 chrono 处理 rust 中的 unix 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68514483/

相关文章:

rust - 我怎样才能将两个 futures 链接到同一个资源上,而不必提前定义每个方法组合?

rust - 如何编写一个 fn 来处理输入并返回迭代器而不是完整结果?

c++ - 使用chrono C++与时间进行比较

c++11 - 如何将 std::chrono::time_point 转换为字符串

vector - 是否可以使用迭代器将向量分成 10 个一组?

c++ - 如何从 stdin 读取多行直到 EOF?

c++ - std::chrono::duration::zero() 的目的是什么

rust - 值(value)活得不够长

c++ - 如何在C++中获取hh:mm:ss.uuuuuu时间戳?