Handling Date and Time in Python

Last updated on Jan 21 2023
Prabhas Ramanathan

Often in data science we need analysis which is based on temporal values. Python can handle the various formats of date and time gracefully. The datetime library provides necessary methods and functions to handle the following scenarios.
• Date Time Representation
• Date Time Arithmetic
• Date Time Comparison
We will study them one by one.

Table of Contents

Date Time Representation

A date and its various parts are represented by using different datetime functions. Also, there are format specifiers which play a role in displaying the alphabetical parts of a date like name of the month or week day. The following code shows today’s date and various parts of the date.
import datetime

 

print 'The Date Today is :', datetime.datetime.today()

date_today = datetime.date.today()
print date_today
print 'This Year :', date_today.year
print 'This Month :', date_today.month
print 'Month Name:',date_today.strftime('%B')
print 'This Week Day :', date_today.day
print 'Week Day Name:',date_today.strftime('%A')

 

When we execute the above code, it produces the following result.
The Date Today is : 2018-04-22 15:38:35.835000
2018-04-22
This Year : 2018
This Month : 4
Month Name: April
This Week Day : 22
Week Day Name: Sunday

Date Time Arithmetic

For calculations involving dates we store the various dates into variables and apply the relevant mathematical operator to these variables.
import datetime


#Capture the First Date
day1 = datetime.date(2018, 2, 12)
print 'day1:', day1.ctime()

# Capture the Second Date
day2 = datetime.date(2017, 8, 18)
print 'day2:', day2.ctime()

# Find the difference between the dates
print 'Number of Days:', day1-day2


date_today = datetime.date.today()

# Create a delta of Four Days 
no_of_days = datetime.timedelta(days=4)

# Use Delta for Past Date
before_four_days = date_today - no_of_days 
print 'Before Four Days:', before_four_days 

# Use Delta for future Date
after_four_days = date_today + no_of_days 
print 'After Four Days:', after_four_days 

When we execute the above code, it produces the following result.
day1: Mon Feb 12 00:00:00 2018
day2: Fri Aug 18 00:00:00 2017
Number of Days: 178 days, 0:00:00
Before Four Days: 2018-04-18
After Four Days: 2018-04-26

Date Time Comparison

Date and time are compared using logical operators. But we must be careful in comparing the right parts of the dates with each other. In the below examples we take the future and past dates and compare them using the python if clause along with logical operators.
import datetime

 

date_today = datetime.date.today()

print 'Today is: ', date_today
# Create a delta of Four Days 
no_of_days = datetime.timedelta(days=4)

# Use Delta for Past Date
before_four_days = date_today - no_of_days 
print 'Before Four Days:', before_four_days

after_four_days = date_today + no_of_days

date1 = datetime.date(2018,4,4)

print 'date1:',date1

if date1 == before_four_days :
print 'Same Dates'
if date_today > date1:
print 'Past Date'
if date1 < after_four_days:
print 'Future Date'

 

When we execute the above code, it produces the following result.
Today is: 2018-04-22
Before Four Days: 2018-04-18
date1: 2018-04-04
Past Date
Future Date

So, this brings us to the end of blog. This Tecklearn ‘Handling Date and Time in Python’ blog helps you with commonly asked questions if you are looking out for a job in Python Programming. If you wish to learn Python and build a career in Python Programming domain, then check out our interactive, Python with Data Science Training, that comes with 24*7 support to guide you throughout your learning period.

Python with Data Science Training

About the Course

Python with Data Science training lets you master the concepts of the widely used and powerful programming language, Python. This Python Course will also help you master important Python programming concepts such as data operations, file operations, object-oriented programming and various Python libraries such as Pandas, NumPy, Matplotlib which are essential for Data Science. You will work on real-world projects in the domain of Python and apply it for various domains of Big Data, Data Science and Machine Learning.

Why Should you take Python with Data Science Training?

• Python is the preferred language for new technologies such as Data Science and Machine Learning.
• Average salary of Python Certified Developer is $123,656 per annum – Indeed.com
• Python is by far the most popular language for data science. Python held 65.6% of the data science market.

What you will Learn in this Course?

Introduction to Python

• Define Python
• Understand the need for Programming
• Know why to choose Python over other languages
• Setup Python environment
• Understand Various Python concepts – Variables, Data Types Operators, Conditional Statements and Loops
• Illustrate String formatting
• Understand Command Line Parameters and Flow control

Python Environment Setup and Essentials

• Python installation
• Windows, Mac & Linux distribution for Anaconda Python
• Deploying Python IDE
• Basic Python commands, data types, variables, keywords and more

Python language Basic Constructs

• Looping in Python
• Data Structures: List, Tuple, Dictionary, Set
• First Python program
• Write a Python Function (with and without parameters)
• Create a member function and a variable
• Tuple
• Dictionary
• Set and Frozen Set
• Lambda function

OOP (Object Oriented Programming) in Python

• Object-Oriented Concepts

Working with Modules, Handling Exceptions and File Handling

• Standard Libraries
• Modules Used in Python (OS, Sys, Date and Time etc.)
• The Import statements
• Module search path
• Package installation ways
• Errors and Exception Handling
• Handling multiple exceptions

Introduction to NumPy

• Introduction to arrays and matrices
• Indexing of array, datatypes, broadcasting of array math
• Standard deviation, Conditional probability
• Correlation and covariance
• NumPy Exercise Solution

Introduction to Pandas

• Pandas for data analysis and machine learning
• Pandas for data analysis and machine learning Continued
• Time series analysis
• Linear regression
• Logistic Regression
• ROC Curve
• Neural Network Implementation
• K Means Clustering Method

Data Visualisation

• Matplotlib library
• Grids, axes, plots
• Markers, colours, fonts and styling
• Types of plots – bar graphs, pie charts, histograms
• Contour plots

Data Manipulation

• Perform function manipulations on Data objects
• Perform Concatenation, Merging and Joining on DataFrames
• Iterate through DataFrames
• Explore Datasets and extract insights from it

Scikit-Learn for Natural Language Processing

• What is natural language processing, working with NLP on text data
• Scikit-Learn for Natural Language Processing
• The Scikit-Learn machine learning algorithms
• Sentimental Analysis – Twitter

Introduction to Python for Hadoop

• Deploying Python coding for MapReduce jobs on Hadoop framework.
• Python for Apache Spark coding
• Deploying Spark code with Python
• Machine learning library of Spark MLlib
• Deploying Spark MLlib for Classification, Clustering and Regression

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Handling Date and Time in Python"

Leave a Message

Your email address will not be published. Required fields are marked *