Qt 时间戳从 Epoch(1970) 到 2000 年开始的 Postgresql 时间戳。如何添加偏移量并将毫秒转换为微秒?

Posted

技术标签:

【中文标题】Qt 时间戳从 Epoch(1970) 到 2000 年开始的 Postgresql 时间戳。如何添加偏移量并将毫秒转换为微秒?【英文标题】:Qt timestamps from Epoch(1970) to Postgresql timestamps that starts in 2000. How to add an offset and convert from milliseconds to microseconds? 【发布时间】:2020-09-29 18:06:37 【问题描述】:

我需要计算从 1970 到 2000 的偏移量以将数据插入 postgresql 数据库,因为 postgresql 以微秒分辨率从 2000 开始,而 currentMSecsSinceEpoch 从 1970 开始以毫秒为单位。 ¿如何添加偏移量以便在 postgresql 数据库中显示相同的日期?

【问题讨论】:

你能告诉我们你的代码哪里有问题吗?当您使用 QDateTime 和时间戳作为数据类型时,您不需要转换任何内容。那么你真正想要实现什么? 对不起,我没有解释它......当我将数据保存到postgresql数据库时,0时间从“2000-01-01 00:00:00”开始;但在 Qt 应用程序中,它从“1970-01-01 00:00:00”开始;。如上所述,分辨率也不同。因此,在将时间戳保存到 postgresql 数据库之前,我需要计算 1970 年和 2000 年之间的差异,否则 postgresql 将在 2050 年保存东西,相差 30 年......我发布了我使用过的解决方案,但如果有另一个解决方案将是很高兴知道! 【参考方案1】:

显示了计算偏移量并转换为微秒的解决方案:

    QString timestamp =  "2000-01-01 00:00:00"; //postgres starts here and uses microseconds resolution
    QString timestampEpoch =  "1970-01-01 00:00:00"; //epoch starts here, Qt has seconds/milliseconds resolution.
    //need to compute the interval between these dates in microseconds
    QString format = "yyyy-MM-dd HH:mm:ss";//TZD";
    QDateTime origin =  QDateTime::fromString(timestampEpoch, format);
    QDateTime end = QDateTime::fromString(timestamp, format);
    qint64 offset = origin.msecsTo(end);
    qint64 timeWithOffset = 1000 * (QDateTime::currentMSecsSinceEpoch() - offset); //mseconds to microseconds for postgresql timestamp(8 bytes)

希望对你有帮助!

【讨论】:

以上是关于Qt 时间戳从 Epoch(1970) 到 2000 年开始的 Postgresql 时间戳。如何添加偏移量并将毫秒转换为微秒?的主要内容,如果未能解决你的问题,请参考以下文章

将时间戳从 Dataframe 加载到 BigQuery 数据集

ESP8266-通过NTP获取 Epoch/Unix(时间戳)时间

为啥 1/1/1970 是“纪元时间”?

PostgreSQL中epoch的用法

C# Epoch 日期时间转换

关于date()