rust - 使用 chrono 处理 rust 中的 unix 时间戳
问题描述
我似乎无法弄清楚如何使用chrono
.
我有以下代码,但是naive
varsdatetime
不正确:
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")
}
解决方案
from_timestamp 不支持毫秒。您可以将毫秒放在第二个参数中作为纳秒。但是你必须把它从时间戳中取出。
查看 substring 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);
}
使用子字符串箱:
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);
}
推荐阅读
- scrapy - 如何将 python 请求与 scrapy 一起使用?
- python - 控制 TensorFlow 中的依赖关系
- javascript - 如何在使用 json_encode() 从 laravel 控制器返回的刀片视图中显示表值?
- toggle - 旨在根据 CapsLock 状态切换的 AHK 脚本始终切换为“关闭”,我无法将其更改为“开启”
- java - 以编程方式连接到 Android 中的隐藏 Wi-Fi 网络?
- vue.js - 使用 v-model 在 Vue 中输入字段不起作用
- php - 在视图 CodeIgniter 中加载视图
- bash - Linux telnet shell 脚本
- sql-server - 从库存表中,找出库存为零的两个日期之间的日期
- javascript - 异步错误处理包装器不起作用