Replies: 1 comment
-
Hi, @efornoni import struct
from datetime import datetime
import snap7
def datetime_to_dat(dt: datetime) -> bytes:
"""
Args:
dt (datetime): A datetime object to be converted.
Returns:
bytes: A byte string in the S7 DATE_AND_TIME format.
The byte string has the following format:
Byte 0: Year (BCD format)
Byte 1: Month (BCD format)
Byte 2: Day (BCD format)
Byte 3: Hour (BCD format)
Byte 4: Minute (BCD format)
Byte 5: Second (BCD format)
Byte 6: Two most significant digits of Millisecond (BCD format)
Byte 7 (4 MSB): Two least significant digits of Millisecond (BCD format)
Byte 7 (4 LSB): Day of week (BCD format)
"""
def int_to_bcd(value: int) -> int:
"""Convert an integer to BCD format"""
return (value // 10) << 4 | (value % 10)
# Check if the year is in the valid range
if dt.year < 1990 or dt.year > 2089:
raise ValueError("Year should be between 1990 and 2089")
# Convert each part of the datetime object to the corresponding byte format
year = int_to_bcd(dt.year % 100)
month = int_to_bcd(dt.month)
day = int_to_bcd(dt.day)
hour = int_to_bcd(dt.hour)
minute = int_to_bcd(dt.minute)
second = int_to_bcd(dt.second)
millisecond_1 = int_to_bcd(dt.microsecond // 1000 // 10)
millisecond_2 = int_to_bcd(dt.microsecond // 1000 % 10)
weekday = int_to_bcd(dt.weekday())
last_byte = millisecond_2 << 4 | weekday
return struct.pack("8B", year, month, day, hour, minute, second, millisecond_1, last_byte)
client = snap7.client.Client()
client.connect("10.10.10.100", 0, 1)
dt = datetime.now()
date_and_time = datetime_to_dat(dt)
client.db_write(db_number=6, start=0, data=date_and_time)
plc_data_and_time = client.db_read(db_number=6, start=0, size=8)
plc_dt = snap7.util.get_date_time_object(plc_data_and_time, 0)
print(dt)
print(plc_dt) Output: >>> 2023-03-30 18:36:21.139895
>>> 2023-03-30 18:36:21.139000 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I wanted to know if anyone had managed to write a date time variable from python to the plc db.
Beta Was this translation helpful? Give feedback.
All reactions