我似乎不知道如何用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")
}发布于 2021-07-25 07:51:45
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);
}发布于 2021-07-25 07:33:27
您的timestamp输入是
1627127393230
1627169482
请注意,您的timestamp偏差了三个数量级,但小数似乎是正确的。所以我猜你的输入-无论你从哪里得到值-在它的表示中都包含了纳秒精度。
如果您知道这是真的,请使用timestamp / 1000和/或将剩余部分混入from_timestamp的第二个参数中。
https://stackoverflow.com/questions/68514483
复制相似问题