mqtt2sql icon indicating copy to clipboard operation
mqtt2sql copied to clipboard

Records created using local time instead of UTC

Open wimleers opened this issue 3 years ago • 1 comments

First: THANK YOU! This allowed me to start collecting data in minutes 👍

After collecting data for a few days, I started noticing that there was something odd about the data: it was all in local time. Which means that when there's a DST change (winter time just started here in Belgium on October 29), the records would be very confusing:

  • …
  • 02:59:58
  • 02:59:59
  • 02:00:00
  • …

i.e. 3 AM becomes 2 AM on October 29.

The even bigger problem: no timezone information is stored! 😨 In fact, the schema claims to store UTC timestamps, but the reality is the opposite:

CREATE TABLE IF NOT EXISTS `mqtt` (
	`id` INTEGER PRIMARY KEY AUTOINCREMENT,
	`ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

👆 This means the default value for ts is the current UTC timestamp.

        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
…
                    sql1 = "INSERT OR IGNORE INTO `{0}` \
                            (ts,topic,value,qos,retain) \
                            VALUES('{1}','{2}',x'{3}','{4}','{5}')"\
                        .format(
                            self.args_.sql_table,
                            timestamp,

☝️ This means that a local timestamp formatted as a UTC timestamp is inserted! This contradicts what the schema claims.

The proper way is:

  1. store in UTC, always — this also prevents DST issues (SQLite: datetime('now') for UTC, datetime('now', 'localtime') for local time)
  2. present in local time, using SELECT datetime(ts, 'localtime') FROM mqtt_history WHERE …;

Would you be willing to accept a PR to change this?

wimleers avatar Nov 04 '23 14:11 wimleers

Went ahead and created a PR: #25.

wimleers avatar Nov 04 '23 14:11 wimleers