Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timezone fix for get_plc_time #306

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions pycomm3/logix_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,24 +335,26 @@ def get_plc_info(self) -> dict:
except Exception as err:
raise ResponseError("Failed to get PLC info") from err

def get_plc_time(self, fmt: str = "%A, %B %d, %Y %I:%M:%S%p") -> Tag:
def get_plc_time(self, fmt: str = "%A, %B %d, %Y %I:%M:%S%p", tz: datetime.timezone = None) -> Tag:
"""
Gets the current time of the PLC system clock. The ``value`` attribute will be a dict containing the time in
3 different forms, *datetime* is a Python datetime.datetime object, *microseconds* is the integer value epoch time,
and *string* is the *datetime* formatted using ``strftime`` and the ``fmt`` parameter.
Gets the current time of the PLC system clock. UTC is returned unless ``tz`` is specified. The ``value`` attribute will
be a dict containing the time in 3 different forms, *datetime* is a Python datetime.datetime object, *microseconds*
is the integer value epoch time, and *string* is the *datetime* formatted using ``strftime`` and the ``fmt`` parameter.

:param fmt: format string for converting the time to a string
:param tz: specific datetime.timezone, local system time if omitted or None
:return: a Tag object with the current time
"""
tag = self.generic_message(
service=Services.get_attribute_list,
class_code=ClassCode.wall_clock_time,
instance=b"\x01",
request_data=b"\x01\x00\x0B\x00",
request_data=b"\x01\x00\x06\x00",
data_type=Struct(n_bytes(6), ULINT("µs")),
)
if tag:
_time = datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=tag.value["µs"])
_time = _time.replace(tzinfo=datetime.timezone.utc).astimezone(tz=tz)
value = {
"datetime": _time,
"microseconds": tag.value["µs"],
Expand All @@ -366,7 +368,8 @@ def set_plc_time(self, microseconds: Optional[int] = None) -> Tag:
"""
Set the time of the PLC system clock.

:param microseconds: None to use client PC clock, else timestamp in microseconds to set the PLC clock to
:param microseconds: None to use client PC clock, else timestamp in microseconds to set the PLC clock to.
Timestamp is uS since epoch 1970-1-1, 00:00 UTC
:return: Tag with status of request
"""
if microseconds is None:
Expand Down