Python 3 Datetime Module Script to Compare and Sort Two Dates Full Example For Beginners

Python 3 Datetime Module Script to Compare and Sort Two Dates Full Example For Beginners

 

Welcome folks today in this blog post we will be comparing two given dates using the built in module called datetime in python. All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to create an app.py file and copy paste the following code

 

app.py

 

# Simple Python program to compare dates 

# importing datetime module 
import datetime 

# date in yyyy/mm/dd format 
d1 = datetime.datetime(2018, 5, 3) 
d2 = datetime.datetime(2018, 6, 1) 

# Comparing the dates will return 
# either True or False 
print("d1 is greater than d2 : ", d1 > d2) 
print("d1 is less than d2 : ", d1 < d2) 
print("d1 is not equal to d2 : ", d1 != d2)

 

See also  Python 3 wxPython Script to Convert Bulk Images to PDF and PDF Merger Using Pillow and PyPDF2 GUI Desktop App Full Project For Beginners

 

Now if you execute the python script by typing the below command as shown below

 

python app.py

 

 

 

Sorting Two Dates

 

See also  Python 3 Tkinter ItemsCanvas Widget to Add Items to Canvas GUI Desktop App Full Project For Beginners

 

Now we will look at an example to sort two given dates in ascending or descending order as shown below

 

app.py

 

# Python program to sort the dates 

# importing datetime module 
from datetime import *

# create empty list 
group = [] 

# add today's date 
group.append(date.today()) 

# create some more dates 
d = date(2015, 6, 29) 
group.append(d) 

d = date(2011, 4, 7) 
group.append(d) 

# add 25 days to the date 
# and add to the list 
group.append(d + timedelta(days = 25)) 

# sort the list 
group.sort() 

# print the dates 
for d in group: 
    print(d)

 

See also  Python Tkinter MultiWindow Fixed Sticky Notes Draggable Notepad GUI Desktop App Full Project For Beginners

 

 

Leave a Reply