Nisbo / another_mvg

MVG/MVV integration for Home Assistant
https://github.com/Nisbo/another_mvg#
MIT License
10 stars 4 forks source link

Faulty timezone conversion #11

Closed spaceboots23 closed 1 week ago

spaceboots23 commented 2 weeks ago

Timezone function doesn't work as intended, but can be fixed by updating the function .replace() with .astimezone() :

Old:

def convert_timestamp_timezone(
    self,
    timestamp: int,
    from_timezone: str,
    to_timezone: str,
    output_format: str = "",
) -> datetime:
    """Convert epoch to timezone datetime."""
    dt = datetime.fromtimestamp(timestamp).replace(tzinfo=ZoneInfo(from_timezone))
    if output_format:
        return dt.replace(tzinfo=ZoneInfo(to_timezone)).strftime(output_format)
    return dt.replace(tzinfo=ZoneInfo(to_timezone))

New:

def convert_timestamp_timezone(
    self,
    timestamp: int,
    from_timezone: str,
    to_timezone: str,
    output_format: str = "",
) -> str:
    """Convert epoch timestamp to timezone-aware datetime and format it."""
    # First, create a timezone-aware datetime object from the timestamp and the from_timezone
    dt = datetime.fromtimestamp(timestamp, tz=ZoneInfo(from_timezone))

    # Convert to the target timezone
    dt_converted = dt.astimezone(ZoneInfo(to_timezone))

    # Return the formatted datetime string if output_format is specified
    if output_format:
    return dt_converted.strftime(output_format)

    return dt_converted
Nisbo commented 2 weeks ago

What was your problem ? What Timezone is set on your HA server ?

The problem was that the API is returning the unix timestamp 1725461340000 (Wed Sep 04 2024 14:49:00 GMT+0000 / Wed Sep 04 2024 16:49:00 GMT+0200) and depending on the settings we have to convert it to ME(S)Z If your server is set to Europe/Berlin, there is no convertion needed. But at least for UTC time zone settings on the server I had to replace the time zone. At least this was the idea to replace the time zone information

spaceboots23 commented 2 weeks ago

All of the arrival/departure times were showing as CEST -2hrs (I suspect that means they were showing as UTC). With the above update they now display as you describe in the readme, when using the from/to flags.

Server settings:

               Local time: Wed 2024-09-04 17:21:25 CEST
           Universal time: Wed 2024-09-04 15:21:25 UTC
                 RTC time: Wed 2024-09-04 15:21:25
                Time zone: Europe/Berlin (CEST, +0200)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
Nisbo commented 2 weeks ago

Maybe I should test a little bit more. ^^ Thx for the fix, I have it already included in my local version.

spaceboots23 commented 2 weeks ago

Hahaha that's what users are for ;) happy to help!