我似乎无法解决如何在Rust中使用chrono
处理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")
}
2条答案
按热度按时间6ioyuze21#
from_timestamp不支持毫秒。你可以把毫秒作为纳秒放在第二个参数中。但是你必须把它从时间戳中分离出来。
检查子字符串crate,或者像这样做:
使用子字符串crate:
n8ghc7c12#
您的
timestamp
输入为1627127393230
current Unix timestamp是
1627169482
请注意,
timestamp
的值相差了3个数量级,但小数似乎是正确的,所以我猜测输入(无论从何处获取值)在表示中包含了纳秒精度。如果您知道这是真的,则使用
timestamp / 1000
和/或将余数混洗到from_timestamp
的第二个参数中。