Skip to content

Commit 3fc91b9

Browse files
committed
* Optimized unix_timestamp_to_iso8601_local_tz()
1 parent 68c0dd5 commit 3fc91b9

File tree

1 file changed

+15
-33
lines changed

1 file changed

+15
-33
lines changed

custom_components/sinapsi_alfa/helpers.py

+15-33
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55

66
import ipaddress
77
import re
8-
import time
9-
from datetime import datetime, timedelta, timezone
8+
from datetime import UTC, datetime
109

1110

1211
def host_valid(host):
@@ -19,40 +18,23 @@ def host_valid(host):
1918
return all(x and not disallowed.search(x) for x in host.split("."))
2019

2120

22-
def get_local_timezone_offset() -> float:
23-
"""Get local timezone offset."""
24-
# Get the current time in seconds since the epoch
25-
current_time = time.time()
26-
27-
# Get the local timezone offset in seconds
28-
local_timezone_offset_seconds = (
29-
-time.timezone
30-
if (time.localtime(current_time).tm_isdst == 0)
31-
else -time.altzone
32-
)
33-
34-
# Convert the offset to hours
35-
local_timezone_offset_hours = local_timezone_offset_seconds / 3600
36-
37-
return local_timezone_offset_hours
38-
39-
4021
def unix_timestamp_to_iso8601_local_tz(unix_timestamp: int) -> str:
41-
"""Convert timestamp to ISO8601."""
22+
"""Convert unix timestamp (UTC) to datetime ISO8601 format with local timezone offset.
4223
43-
# Convert Unix timestamp to datetime object in UTC
44-
dt_utc = datetime.utcfromtimestamp(unix_timestamp).replace(tzinfo=timezone.utc) # noqa: UP017
24+
Args:
25+
unix_timestamp (int): Unix timestamp in seconds since the epoch.
4526
46-
# Get the local timezone offset
47-
local_timezone_offset_hours = get_local_timezone_offset()
27+
Returns:
28+
str: ISO8601 formatted datetime string with local timezone offset.
4829
49-
# Create a timezone object with the local offset
50-
local_timezone = timezone(timedelta(hours=local_timezone_offset_hours))
30+
Example:
31+
>>> unix_timestamp_to_iso8601_local_tz(1739238065) in CET timezone
32+
'2025-02-11T02:41:05+01:00'
5133
52-
# Convert UTC datetime to local datetime
53-
dt_local = dt_utc.astimezone(local_timezone)
34+
"""
5435

55-
# Format local datetime object as ISO8601 string
56-
iso8601_format = dt_local.isoformat()
57-
58-
return iso8601_format
36+
return (
37+
datetime.fromtimestamp(timestamp=unix_timestamp, tz=UTC)
38+
.astimezone()
39+
.isoformat()
40+
)

0 commit comments

Comments
 (0)