TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Datetime Explained with Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python AdvancedPython Tutorials

Python Datetime Explained with Examples

Last updated: Oct 28, 2023 8:15 pm
By Meenakshi Agarwal
Share
7 Min Read
Python Datetime Module Functions with Examples
Python Datetime Module Functions with Examples
SHARE

This tutorial explains how to work with the date and time values using Python datetime. This module provides classes for representing and manipulating dates and times.

Contents
Introduction to Datetime ModuleHow to Use Datetime Module in Python ProgramsPython Datetime ExamplesTo display today’s date we use the following code:To view the individual date components, we need:Find out the weekday of the current date:

Please note that this module and its functions could come in quite handy for a variety of applications such as:

-Display dates and times on web pages and perform date- and time-related calculations.
-Analyze and visualize data that contains dates and times.
-Automate tasks that require working with dates and times.
-Calculate financial metrics that depend on dates and times.

How to Use Date and Time in Python

Greetings, hope you had a great day. Today, we plan to educate you on how to find the date, day, time, etc. using a module known as the datetime in Python.

You should be comfortable with modules in Python before studying the concept of date and time objects in Python. This tutorial uses syntax for Python3 which can be modified for use with Python2.

Pre-requisites

You need to have some level of experience using the modules in Python. They provide readymade functions that you can directly call from any program.

Introduction to Datetime Module

Although we can use the time module to find out the current date and time, it lacks features such as the ability to create Date objects for a particular manipulation.

To remedy this, Python has a built-in datetime module. Hence, to do any object manipulation regarding date and time, we need to import datetime module.

The datetime module is used to modify date and time objects in various ways. It contains five classes to manipulate date and time. They are shown in the below table:

Python Datetime ClassesShort Description
dateThis class deals with date objects.
timeIt works with time objects.
datetimeIt deals with date and time object combinations.
timedeltaThis class provides functionality related to intervals of time. Used in calculations of past and future date and time objects.
infoIt deals with time zone info of local time.

We are going to deal with these date and time classes in the example section.

How to Use Datetime Module in Python Programs

To create and modify new date and time objects, we need to import the module. We load them by using the following statement.

import datetime

Or if you want only one of the modules-

from datetime import date

from datetime import time

from datetime import datetime

We could create new objects that have different date and time values stored for manipulation using the Python datetime module.

The following syntax would do the needful. It is just the pseudo-code.

import datetime

datetime.datetime(year_number, month_number, date_number, hours_number, minutes_number, seconds_number)

To format the dates into human-readable strings, we use the function strftime() that is available in the datetime module.

The datetime module has another function timedelta() . It allows calculations on the date and time objects and is useful for doing time operations.

The syntax used in invoking timedelta() is as follows:

from datetime import timedelta

timedelta(days, hours, minutes, seconds, year,...)

Python Datetime Examples

You can copy/paste the below code either in a Python interpreter or in an online Python compiler and run it.

To display today’s date we use the following code:

import datetime

print (datetime.date.today())

Or

from datetime import date

print (date.today())

To view the individual date components, we need:

Python datetime provides the date class which keeps track of all date and time components. The below code illustrates how can we access them.

from datetime import date

print (date.today().day)

print (date.today().month)

print (date.today().year)

#If you prefer to write in one sentence, write it as 

print (date.today().day,date.today().month,date.today().year)

Since the above code is long, we can rewrite it as:

from datetime import date

now = date.today()

print (now.day)

print (now.month)

print (now.year)

#You can also display the previous 3 sentences in one sentence 

print (now.day, now.month, now.year)

This code is cleaner and compact. Try to write the code in the shortest way possible without affecting readability.

The below picture shows the output of the code if you run it from the Python command line interface:

Python Datetime Example-1

Find out the weekday of the current date:

You could also use the date class from Python datetime to find out the weekday of the current date:

from datetime import date

now = date.today()

print (f"The week of the day is {now.weekday()}")

The following is the output of the above code:

The week of the day is 4.

To format the date and time into human-readable strings, we use strftime() in the datetime module.

The following example clarifies how to use this function and prints the date/time in a styled manner:

import datetime
from datetime import datetime as tm

Today = tm.now()

print (Today.strftime("%a, %B, %d, %y"))

When you run it, you get the following output. Basically, all the date components print separately.

Fri, October, 13, 23

It is important to understand the format codes used in the above code.

Format CodeShort Description
%arefers to the day
%B
refers to the month
%d
refers to the date
%yrefers to the year

The above codes are the most common format types to use in Python datetime programs.

However, if you want to print the local date and time using the function strftime() like the way given in the following example.

import datetime
from datetime import datetime as tm

Today = tm.now()

print ("Today’s date is " ,Today.strftime("%c"))

To display only the local date and local time separately, instead of%c use %x.

The following is a sample Python Program using multiple date-time modules.

from datetime import date,time, datetime, timedelta

# Time_gap is the timedelta object where
# we can do different calculations on it.

Time_gap = timedelta(hours = 23, minutes = 34)

print ("Future time is" , str(datetime.now() + Time_gap))

The output is as follows.

Python Datetime Example-3

Conclusion – Usages of Datetime Module

Python Datatime It is a powerful feature that allows us to manipulate the system’s date and time without risking any system changes. We can define a new date object and modify its representation.

Arithmetic calculations can be done on the date and time objects for several purposes such as finding the future date, and the present year, formatting of date value into a string, creating a time management solution, etc.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Module - A Step by Step Tutorial for Beginners Python Module Explained with Examples
Next Article Learn Python Regular Expression with Examples How to Use Regular Expression in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x