DEV Community

Cover image for Build a Product Receipt Generator using Python.
Ebikara Spiff
Ebikara Spiff

Posted on • Edited on

Build a Product Receipt Generator using Python.

Introduction

Did you know you can create your Product Receipt Generator using only Python and the datetime module? In this article, we will cover how to use the datetime module to automate the process of generating receipts.

Python is a versatile tool, and today we're delving into a practical use case that can simplify your daily routines. With the datetime module at your disposal, handling dates and times becomes a breeze, making it perfect for crafting accurate and dynamic product receipts. Whether you're a seasoned Python pro or just starting your coding journey, this article will guide you through each step with ease.

Let's start coding.

Setting up the Environment

To begin, we'll set up our coding environment in Replit.

Step 1

First, head to the Python section on the homepage to create a new file.

Replit Homepage

Step 2

You can name your new file or stick with the one automatically provided.

new Python file

Step 3

Our first task is to import the necessary library by typing import datetime.:



Import datetime


Enter fullscreen mode Exit fullscreen mode

Understanding the Structure of a Product Receipt

To create a Product Receipt Generator in Python, you need to define a data structure to store details such as transaction date and time, purchased items (with name, quantity, price, and total cost), taxes, discounts, and the final total.

Step 1

We'll create the header of our receipt by defining variables for the store name, address, phone number, and cashier's name.:



store_name = "Super grocery mart"
store_street = "Orlando, FL 32803"
store_phone_number = "(407)555-1234"
cashier_name = "Jane Smith"


Enter fullscreen mode Exit fullscreen mode

Step 2

Now, let's use the datetime library to set up the date and time for our receipt:



now = datetime.datetime.now()


Enter fullscreen mode Exit fullscreen mode

Step 3

Here, Let's format the datetime on our receipt to have a year/month/day format and also include the hour/minute/second details. This can be done using 'Strf time' :



date_time = now.strftime("%Y-%m-%d %H:%M:%S")


Enter fullscreen mode Exit fullscreen mode

Generating Product Data

So, when you're creating a product receipt generator using Python, part of the process involves setting up a database with all the necessary product information. This data usually consists of things like product names, prices, quantities, and maybe even descriptions.

Step 1

Let's create a list of the items you purchased and their prices. Let's make this receipt look great

sgm spaghetti sauce - 4.99
sgm spaghetti pasta - 1.99
mrchn inst lunch - 0.96
ee coffee french rst - 5.96
sgm evrdy pnt btr - 1.99
cub white bread - 1.99
par baked rustic rolls - 4.99

Step 2

In this step, we will create a variable for each product and also define it's name and price. This setup allows us to organize the items and their costs efficiently for calculation:



p1_name, p1_price = "sgm spaghetti sauce", 4.99
p2_name, p2_price = "sgm spaghetti pasta", 1.99
p3_name, p3_price = "mrchn inst lunch", 0.96
p4_name, p4_price = "ee coffee french rst", 5.96
p5_name, p5_price = "sgm evrdy pnt btr", 1.99
p6_name, p6_price = "cub white bread", 1.99
p7_name, p7_price = "par baked rustic rolls", 4.99


Enter fullscreen mode Exit fullscreen mode

Step 3

Next, we will write down the total number of items sold. This is noted to keep track of how many products were included in the transaction.:



items_sold = 7


Enter fullscreen mode Exit fullscreen mode

Building the Receipt Generator

So, now that we've got a good grasp of the product receipt structure and our product data is all set, it's time to dive into building our receipt generator.

Step 1

First, we want to calculate the subtotal of our grocery list, Calculating the subtotal is crucial.
This adds up the prices of all the products, giving us the total cost before applying taxes:



subtotal = p1_price + p2_price + p3_price + p4_price + p5_price + p6_price + p7_price


Enter fullscreen mode Exit fullscreen mode

Step 2

Next, let's calculate our food tax. By applying a food tax rate of 6% to the subtotal, we compute the amount of tax owed. This ensures that the tax is accurately represented on the receipt:



food_tax = ( sub_total * 0.06)


Enter fullscreen mode Exit fullscreen mode

Step 3

Now, we calculate the grand total, The grand total reflects the total amount the customer needs to pay for the entire purchase.

To do this, we will add the subtotal and the calculated food tax.:



grand_total = sub_total + food_tax


Enter fullscreen mode Exit fullscreen mode

Customizing and Printing a Receipt

When you're creating a product receipt generator in Python, customizing and printing the receipt is super important. This helps give users a clear and professional document.

Step 1

In this step, let's define the return and appreciation messages for our grocery store.
The return message states the policy for certain items, and the appreciation message thanks the customers for their business.:



return_message = No returns on meat, product, milk products.
appreciate _message  = Thank you for your business !! 


Enter fullscreen mode Exit fullscreen mode

Step 2

Now, let's start designing the receipt header by printing out the store's name, address, and phone number and creating a structured display using print statements and formatting:



print(* * 49 )
print(f\t\t\t\t{store_name.title( )})
print(f\t\t\t\t{store_street})
print(f\t\t\t\t{store_phone_number})
print(= * 49)


Enter fullscreen mode Exit fullscreen mode

Step 3

Let's save our progress and run the code to see the header printed.

receipt header

Step 4

Next, we will add the cashier's name to the header to personalise the receipt further. :



print(fCashier: {cashier_name})


Enter fullscreen mode Exit fullscreen mode

Step 5

Next, we want to print our date and time and to do this, we will use string indexing and slicing to separate and space the date and time on the receipt:



print(f{date_time[0:10]}/t/t/t/t/t/t/t/t{date_time[10: ]})
print(= * 49)


Enter fullscreen mode Exit fullscreen mode

Step 6

Let's save and run the code to ensure the date and time are displayed correctly.

Image of receipt date and time

Step 7

Now, we will print the grocery list items with their corresponding prices as the receipt body to show the purchased items:



print (GROCERY )
print(  )
print(f{p1_name.upper( )}\t\t\t\t\t\t{p1_price})
print(f{p2_name.upper( )}\t\t\t\t\t\t{p2_price})
print(f{p3_name.upper( )}\t\t\t\t\t\t{p3_price})
print(f{p4_name.upper( )}\t\t\t\t\t{p4_price})
print(f{p5_name.upper( )}\t\t\t\t\t\t{p5_price})
print(f{p6_name.upper( )}\t\t\t\t\t\t{p6_price})
print(f{p7_name.upper( )}\t\t\t\t\t\t{p7_price})
print ( )
print(= * 49)


Enter fullscreen mode Exit fullscreen mode

Step 8

Let's save and run to verify that the grocery list is printed correctly.

Image of grocery list on receipt

Step 9

Next, let's print out our subtotal, food tax, and total to outline our financial details of the purchase, and we will also ensure the amounts are rounded to two decimal places:



print(fSubtotal \t\t\t\t\t\t\t\t   ${sub_total:.2f})

print(fFood Tax @ 6% \t\t\t\t\t\t\t\t   ${food_tax:.2f})

print(fGRAND TOTAL  \t\t\t\t\t\t\t\t   ${grand_total:.2f})

print(= * 49)


Enter fullscreen mode Exit fullscreen mode

(2f) This is to convert the figure to 2 decimal places after calculating.

Step 10

Now, let's save and run the code to check the accuracy of the calculation and display of our financial summary.

Image of receipt financial summary

Step 11

In this step, we will print the total number of items sold to provide a summary of the quantity of products purchased:



print(  ) 
print(f TOTAL NUMBER OF ITEMS SOLD = \t\t\t\t\t   {items_sold})
print(  )
print( )


Enter fullscreen mode Exit fullscreen mode

Step 12

Finally, we will display the return items message and the appreciation message to communicate the store's policies and gratitude to customers.:



print(f\t{return_message})
print(f\t\t\t{appreciation_message})


Enter fullscreen mode Exit fullscreen mode

Step 13

Save and run the complete code to generate the final receipt with all the customized information displayed in a structured manner.

Image of final receipt

Conclusion

In addition to the convenience and efficiency that the datetime module brings to building a product receipt generator in Python, there are several other advantages to consider. One key benefit is the flexibility to customize the receipt format according to your business requirements. You can easily adjust the date and timestamp display formats, include time zones, or incorporate specific time-related details to meet the unique needs of your business.

Integrating the datetime module in your product receipt generator allows you to maintain accurate and consistent timestamps on each receipt, ensuring reliable record-keeping and traceability. This not only enhances the professionalism and credibility of your business but also assists in tracking transactions and providing transparency to your customers.

Top comments (7)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
spiff profile image
Ebikara Spiff

Thanks. Please let me know when you do

Collapse
 
masonericd profile image
masonericd

Thanks. I am thinking if a logo can be included on the receipt.

Collapse
 
spiff profile image
Ebikara Spiff • Edited

Of course, you can add any logo of your choice to further enhance your receipt using the Python Imaging Library (PIL) which is now Known as Pillow Library.

Collapse
 
naijasolutions profile image
godwin osagie

Hi Ebi,
Thanks for this knowledge, i really appreciate.
The challenge i encountered is that when i carried out step 3 under customizing and printing receipt, nothing came up on the console.

Why is that?

Collapse
 
naijasolutions profile image
godwin osagie

Hi Ebi, I was able to finally sort it out.

Thanks

Collapse
 
naijasolutions profile image
godwin osagie • Edited

Error message - (function) datetime: unknown

AttributeError: 'str' object has no attribute 'datetime'