我一直在try ,但这很难,因为类型并不完全匹配.

我目前的try 是:

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 DB中的存储方式.

推荐答案

chrono has a method to convert ms since epoch to NaiveDateTime...但time并非如此.

经过大量研究,我发现IS有一种方法可以将它们转换为OffsetDateTime:from_unix_timestamp_nanos()(只有秒和纳秒的方法,没有毫秒的方法).但没有方法可以将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);
}

Postgresql相关问答推荐

PostgreSQL:`row_alias为null`且`row_alias不是null`返回值不一致

单个WAL文件中的操作会影响哪些表和多少行

即使存在 GIN 索引,整理默认的类似查询也无法执行

在 jOOQ 中使用 $$ 引用字符串

如何通过 DirectFunctionCall 发送 NULL 参数?

是否可以短时间运行 VACUUM FULL 并获得一些好处?

gorm 创建并返回值 many2many

Regexp_replace 行为会改变,如果它用空白字符串或 null 替换字符串数组中的字符串

如何为基于复合类型的 Postgres DOMAIN 定义 CHECK 约束

如何防止 PDO 将问号解释为占位符?

PostgreSQL比较两个jsonb对象

postgreSQL 中对 utf-8 的 LC_COLLATE 和 LC_CTYPE 支持

postgresql中的外键可以被触发器违反

如何 Select 列值为空的行?

Postgres UPDATE with ORDER BY,怎么做?

从 PostgreSQL 序列中 Select 多个 id

你如何在postgresql中做mysqldump?

在 PostgreSQL 中跳过每 n 个结果行

每个数据库提供程序类型允许的最大参数数是多少?

有没有办法确保 WHERE 子句在 DISTINCT 之后发生?