【问题标题】:Storing DateTime in PostgreSQL without loosing precision [duplicate]在不丢失精度的情况下在 PostgreSQL 中存储 DateTime [重复]
【发布时间】:2018-12-08 18:13:18
【问题描述】:

我遇到了一个问题,即每当我从 Postgresql 数据库加载大概是 DateTime 的内容并将其与 C# 的初始值进行比较时,数据就会不匹配。例如,这是 C# 中的原始 DateTime

日期:{09.07.2018 00:00:00}

报价:636667391123714378

时间:{13:18:32.3714378}

同一日期,从DB 返回(保存后):

日期:{09.07.2018 00:00:00}

报价:636667391123714370

时间:{13:18:32.3714370}

似乎在保存时 - DateTime 失去了一些精度。数据库中的列类型是Timestamp。所以,2个问题:

  1. DateTime 存储在PostgreSQL 中的正确方法是什么,这样我就不会丢失任何精度?

我正在考虑将 UNIX 毫秒数保存到 Integer 字段中,而不是将 DateTime 保存为 Timestamp,即:

DateTime myDT = DateTime.Now;
long ms = new DateTimeOffset(myDT).ToUnixTimeMilliseconds();

// how I do it now
var parameterOld =
    new Npgsql.NpgsqlParameter("dateInserted", NpgsqlTypes.NpgsqlDbType.Timestamp) {Value = myDT };

// how I think would be a better approach
var parameterNew =
    new Npgsql.NpgsqlParameter("dateInserted", NpgsqlTypes.NpgsqlDbType.Integer) { Value = ms };
  1. 或者,如何以尽可能高的精度 (C#/PostgreSql) 比较 2 个日期时间?

我目前的解决方案,有点工作.. 但我在这里失去了太多的精度:

public static bool IsEqualWithLossOfPrecision(this DateTime timestamp1, DateTime timestamp2)
{
    return (
        timestamp1.Year == timestamp2.Year &&
        timestamp1.Month == timestamp2.Month &&
        timestamp1.Day == timestamp2.Day &&
        timestamp1.Hour == timestamp2.Hour &&
        timestamp1.Minute == timestamp2.Minute &&
        timestamp1.Millisecond == timestamp2.Millisecond
    );
}

欢迎任何关于 2 个问题的建议。

我正在使用最新可用版本的 DB (10.4)、Npgsql library v. 4.0.0、.net framework 4.5ish、windows 10

【问题讨论】:

    标签: c# postgresql datetime timestamp


    【解决方案1】:

    PostgreSQL 时间戳的精度限制为微秒。

    如果您需要更多,请将纳秒存储在单独的 bigint 属性中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2012-05-03
      • 1970-01-01
      • 2013-02-03
      • 2021-10-21
      相关资源
      最近更新 更多