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.
Step 2
You can name your new file or stick with the one automatically provided.
Step 3
Our first task is to import the necessary library by typing import datetime
.:
Import datetime
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"
Step 2
Now, let's use the datetime library
to set up the date and time for our receipt:
now = datetime.datetime.now()
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")
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
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
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
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)
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
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 !! “
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)
Step 3
Let's save our progress and run the code to see the header printed.
Step 4
Next, we will add the cashier's name to the header to personalise the receipt further. :
print(f”Cashier: {cashier_name}”)
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)
Step 6
Let's save and run the code to ensure the date and time are displayed correctly.
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)
Step 8
Let's save and run to verify that the grocery list is printed correctly.
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(f”Subtotal \t\t\t\t\t\t\t\t ${sub_total:.2f}”)
print(f”Food Tax @ 6% \t\t\t\t\t\t\t\t ${food_tax:.2f}”)
print(f”GRAND TOTAL \t\t\t\t\t\t\t\t ${grand_total:.2f}”)
print(“=“ * 49)
(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.
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(“ “)
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}”)
Step 13
Save and run the complete code to generate the final receipt with all the customized information displayed in a structured manner.
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 (6)
Thanks. Please let me know when you do
Thanks. I am thinking if a logo can be included on the receipt.
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.
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?
Error message - (function) datetime: unknown
AttributeError: 'str' object has no attribute 'datetime'