The solution is using a library which supports GS1 DataMatrix codes and then create a file out of it.
The one for you is treepoem, which identifies the values, adds FNC1 as a starting character and GS characters where needed.
Here is a simple script to generate correctly, you might have to adjust the data content and options to your needs.
from treepoem import generate_barcode
from PIL import Image
def generate_and_print(gtin, serial_number, expiry_date, batch_number):
# Generate datamatrix
datamatrix = generate_barcode(
barcode_type='gs1datamatrix',
data=f"(01){gtin}(21){serial_number}(17){expiry_date}(10){batch_number}",
options={"parsefnc": True, "format": "square", "version": "26x26"})
# Resize datamatrix to desired size
dm_size_px = (120, 120)
datamatrix = datamatrix.resize(dm_size_px, Image.NEAREST)
# Create white picture
picture_size_px = (200, 200)
picture = Image.new('L', picture_size_px, color='white')
# Position the datamatrix
barcode_position_px = (40, 40)
picture.paste(datamatrix, barcode_position_px)
# Save the image
picture.save("datamatrix.png")
gtin = "01234567890128"
serial_number = "01234567891011"
expiry_date = "250731"
batch_number = "DATAMATRIXTEST"
generate_and_print(gtin, serial_number, expiry_date, batch_number)