Skip to content

Commit

Permalink
Ensured correct timezone handling observing Daylight Savings Time, wh…
Browse files Browse the repository at this point in the history
…en parsing the received timestamp from the EVSE device.
  • Loading branch information
slespersen committed Dec 3, 2024
1 parent abe2d1d commit ca2ba2b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
3 changes: 2 additions & 1 deletion evseMQTT/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,11 @@ def name(data, identifier):
def system_time(data, identifier):
epoch = Utils.bytes_to_int_little(data[1:5])
local_time = Utils.bytes_to_timestamp(epoch)
local_epoch = Utils.bytes_to_timezoned_epoch(epoch)

return {
"system_time": local_time,
"system_time_raw": epoch
"system_time_raw": local_epoch
}

def system_language(data, identifier):
Expand Down
40 changes: 38 additions & 2 deletions evseMQTT/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import struct
import zoneinfo
from .constants import Constants
from datetime import datetime, timezone, timedelta

Expand Down Expand Up @@ -155,11 +156,46 @@ def timestamp_bytes():

return list(timestamp_bytes)


@staticmethod
def bytes_to_timestamp(bytes):
local_time = datetime.fromtimestamp(bytes)
# Define the Asia/Shanghai timezone offset manually (+8 hours from UTC)
shanghai_offset = timedelta(hours=8)

# Convert the Unix epoch timestamp to a datetime object in the Asia/Shanghai timezone
shanghai_time = datetime.utcfromtimestamp(bytes) + shanghai_offset

# Now convert this to the system's local time zone
# Get the current local timezone offset including DST
local_time = datetime.now()
local_offset = local_time.utcoffset() if local_time.utcoffset() else timedelta(0)

# Convert Shanghai time to the system's local time
local_time = shanghai_time - local_offset

return local_time.isoformat()


@staticmethod
def bytes_to_timezoned_epoch(bytes):
# Define the Asia/Shanghai timezone offset manually (+8 hours from UTC)
shanghai_offset = timedelta(hours=8)

# Convert the Unix epoch timestamp to a datetime object in the Asia/Shanghai timezone
shanghai_time = datetime.utcfromtimestamp(bytes) + shanghai_offset

# Now convert this to the system's local time zone
# Get the current local timezone offset including DST
local_time = datetime.now()
local_offset = local_time.utcoffset() if local_time.utcoffset() else timedelta(0)

# Convert Shanghai time to the system's local time
local_time = shanghai_time - local_offset

# Convert the local time back to a Unix epoch timestamp
local_timestamp = int(local_time.timestamp())

return local_timestamp

@staticmethod
def device_name(name):
# Convert string to bytes
Expand Down

0 comments on commit ca2ba2b

Please sign in to comment.