提问人:Antonin GAVREL 提问时间:10/4/2023 最后编辑:Antonin GAVREL 更新时间:10/5/2023 访问量:67
将整数(纪元时间(以毫秒为单位)转换为 PrimitiveDateTime
Convert integer (epoch time in ms) to PrimitiveDateTime
问:
我一直在尝试,但这很困难,因为类型不完全匹配。
我目前的尝试:
use ::time::{PrimitiveDateTime, OffsetDateTime};
use std::time::{UNIX_EPOCH, Duration};
use chrono::{DateTime, Utc, NaiveDateTime};
fn my_func() {
let timestamp:u64 = 1696443084 // {integer from http request, representing timestamp in ms since epoch}
let d:SystemTime = UNIX_EPOCH + Duration::from_secs(timestamp/1000);
let datetime:DateTime<Utc> = DateTime::<Utc>::from(d); // ideally want to replace this line with one where I get a DateTime (and not DateTime<Utc>) from the integer.
let created_at:PrimitiveDateTime = PrimitiveDateTime::new(datetime.date_naive(), datetime.time());
}
我的错误消息(编译)如下:
106 | ... = PrimitiveDateTime::new(datetime.date_naive(), datetime.time(...
| ^^^^^^^^^^^^^^^^^^^^^^ --------------------- --------------- expected `Time`, found `NaiveTime`
| |
| expected `Date`, found `NaiveDate`
|
note: associated function defined here
--> /.../time-0.3.23/src/primitive_date_time.rs:92:18
|
92 | pub const fn new(date: ...
| ^^^
我需要使用 PrimitiveDateTime,因为这是时间戳在 psql 数据库中的存储方式。
答:
1赞
Chayim Friedman
10/5/2023
#1
chrono
有一种方法可以将 ms since epoch 转换为 NaiveDateTime
...但事实并非如此。time
经过大量研究,我发现有一种方法可以将它们转换为:from_unix_timestamp_nanos()(
只有秒和纳秒的方法,毫秒没有方法)。但是没有方法可以将 转换为 ,但似乎有效。OffsetDateTime
OffsetDateTime
PrimitiveDateTime
PrimitiveDateTime::new(dt.date(), dt.time())
所以:
use time::{OffsetDateTime, PrimitiveDateTime};
fn main() {
let timestamp: u64 = 1696443084; // {integer from http request, representing timestamp in ms since epoch}
let created_at =
OffsetDateTime::from_unix_timestamp_nanos(i128::from(timestamp) * 1_000_000).unwrap();
let created_at = PrimitiveDateTime::new(created_at.date(), created_at.time());
dbg!(created_at);
}
评论
0赞
Antonin GAVREL
10/5/2023
了不起!非常感谢:)
评论
chrono
中没有PrimitiveDateTime
。请创建一个最小可重复示例,并为每种类型说明它来自哪个板条箱。use
cargo check
PrimitiveDateTime
time
chrono