Intellipaat

Intellipaat

Explore Online Courses Free Courses Hire from us Become an Instructor Reviews
All Courses
  • Articles
  • Tutorials
  • Interview Questions
Home > Blog > Tutorials > Python Tutorial For Beginners > Python Datetime – A Guide to Work With Dates and Times in Python

Python Datetime – A Guide to Work With Dates and Times in Python

By Lithin Reddy | Last updated on July 18, 2025 | 87972 Views
Share this article
Previous
Next
Tutorial Playlist
  • Python Tutorials

    • Python Tutorial For Beginners
    • Introduction and History of Python
    • Python Download – How To Install Python [Easy Steps]
    • Python Version History
    • What is Python Programming Language?
    • Advantages and Disadvantages of Python
    • Python Data Types: Complete Guide with Examples (2026)
    • Python Arrays – The Complete Guide
    • Strings in Python
    • Python Numbers – Learn How to Create Prime Numbers, Perfect Numbers, and Reverse Numbers in Python
    • Python Classes and Objects
    • Python for Loops – A Step-by-Step Guide
    • Python If Else Statements – Conditional Statements with Examples
    • Python Syntax: A Guide To Writing Basic Python Code
    • Python JSON – Parsing, Creating, and Working with JSON Data
    • File Handling in Python
    • Introduction to Python Modules
    • Python Operators
    • Enumerate() in Python – A Detailed Explanation
    • Python Set – The Basics
    • Python Datetime – A Guide to Work With Dates and Times in Python
    • Python Lists – A Complete Guide (With Syntax and Examples)
    • How to Install Pip in Python
    • What are comments in python
    • Tokens in Python – Definition, Types, and More
    • How to Take List Input in Python – Python List Input
    • Tuples in Python
    • Python Function – Example & Syntax
    • What is Regular Expression in Python
    • Python Modules, Regular Expressions & Python Frameworks
    • How to Sort a List in Python Without Using Sort Function
    • How to Compare Two Strings in Python?
    • What is Type Casting in Python with Examples?
    • List vs Tuple in Python
    • Identifiers in Python
    • A Complete Guide to Data Visualization in Python
    • What is Recursion in Python?
    • Python Lambda Functions – A Beginner’s Guide
    • List Comprehension in Python
    • Python Built-in Functions
    • Dictionaries in Python – From Key-Value Pairs to Advanced Methods
    • Python Input and Output Commands
    • Web Scraping with Python – A Step-by-Step Tutorial
    • Exception Handling in Python with Examples
    • Numpy – Features, Installation and Examples
    • Python Pandas – Features and Use Cases (With Examples)
    • SciPy in Python Tutorial
    • Introduction to Matplotlib in Python
    • Scikit-Learn Cheat Sheet: Python Machine Learning
  • Python Tutorials

    • Python Tutorial For Beginners
    • Introduction and History of Python
    • Python Download – How To Install Python [Easy Steps]
    • Python Version History
    • What is Python Programming Language?
    • Advantages and Disadvantages of Python
    • Python Data Types: Complete Guide with Examples (2026)
    • Python Arrays – The Complete Guide
    • Strings in Python
    • Python Numbers – Learn How to Create Prime Numbers, Perfect Numbers, and Reverse Numbers in Python
    • Python Classes and Objects
    • Python for Loops – A Step-by-Step Guide
    • Python If Else Statements – Conditional Statements with Examples
    • Python Syntax: A Guide To Writing Basic Python Code
    • Python JSON – Parsing, Creating, and Working with JSON Data
    • File Handling in Python
    • Introduction to Python Modules
    • Python Operators
    • Enumerate() in Python – A Detailed Explanation
    • Python Set – The Basics
    • Python Datetime – A Guide to Work With Dates and Times in Python
    • Python Lists – A Complete Guide (With Syntax and Examples)
    • How to Install Pip in Python
    • What are comments in python
    • Tokens in Python – Definition, Types, and More
    • How to Take List Input in Python – Python List Input
    • Tuples in Python
    • Python Function – Example & Syntax
    • What is Regular Expression in Python
    • Python Modules, Regular Expressions & Python Frameworks
    • How to Sort a List in Python Without Using Sort Function
    • How to Compare Two Strings in Python?
    • What is Type Casting in Python with Examples?
    • List vs Tuple in Python
    • Identifiers in Python
    • A Complete Guide to Data Visualization in Python
    • What is Recursion in Python?
    • Python Lambda Functions – A Beginner’s Guide
    • List Comprehension in Python
    • Python Built-in Functions
    • Dictionaries in Python – From Key-Value Pairs to Advanced Methods
    • Python Input and Output Commands
    • Web Scraping with Python – A Step-by-Step Tutorial
    • Exception Handling in Python with Examples
    • Numpy – Features, Installation and Examples
    • Python Pandas – Features and Use Cases (With Examples)
    • SciPy in Python Tutorial
    • Introduction to Matplotlib in Python
    • Scikit-Learn Cheat Sheet: Python Machine Learning
`; ip_get_section_iq.innerHTML = sidebarhtml_desk; playlistmobile.innerHTML = sidebarhtml_desk; var ip_iq_scriptToRemove = document.getElementById('ip-blog-iq-script-removal'); if (ip_iq_scriptToRemove) { ip_iq_scriptToRemove.remove(); } var activeSubmenuItems = document.querySelectorAll('.tutorial_list_submenu li.active'); activeSubmenuItems.forEach(function(activeItem) { var rootParentLi = activeItem.closest('.maincata'); if (rootParentLi) { rootParentLi.classList.add('opentutorialsubmenu'); } }); var ip_blog_tutorialListMenu = document.querySelector('.tutorial_list_menu'); if(ip_blog_tutorialListMenu){ var ip_blo_activeItem = ip_blog_tutorialListMenu.querySelector('li.active'); var lastlink = ''; var nextlink = ''; var total = 0; jQuery('#TutorialLeftArea .maincata ul').children('li').each(function(indexx) { total = indexx; }); jQuery('#TutorialLeftArea .maincata ul').children('li').each(function(i) { var isActive = jQuery(this).hasClass('active'); if(isActive){ if(i !== 0){ var lastIndexedElement = jQuery('#TutorialLeftArea .maincata ul').children('li').eq(i - 1); lastlink = lastIndexedElement.children('a').attr('href'); }else{ lastlink = ''; } if(total > i){ var nextIndexedElement = jQuery('#TutorialLeftArea .maincata ul').children('li').eq(i + 1); nextlink = nextIndexedElement.children('a').attr('href'); }else{ nextlink = ''; } return false; } }); var ip_blog_prevBlog = document.querySelector('.prev-blog a'); var ip_blog_nextBlog = document.querySelector('.next-blog a'); if (lastlink !== '' && typeof lastlink !== 'undefined') { ip_blog_prevBlog.setAttribute('href', lastlink); }else { if(ip_blog_prevBlog){ ip_blog_prevBlog.style.display = 'none'; } } if (nextlink !== '' && typeof nextlink !== 'undefined') { ip_blog_nextBlog.setAttribute('href', nextlink); }else { if(ip_blog_nextBlog){ ip_blog_nextBlog.style.display = 'none'; } } } function ip_blog_setActiveLink() { var divElements = document.querySelectorAll('div[id]'); var links = document.querySelectorAll('.interview-question-bookmark-list-alt li a'); var activeLink = null; divElements.forEach(function(div) { if (ip_blog_isInViewportThreshold(div, 50)) { var ip_blog_divId = div.getAttribute('id'); links.forEach(function(link) { if (link.getAttribute('href') === '#' + ip_blog_divId) { activeLink = link; } }); } }); links.forEach(function(link) { link.classList.remove('active'); }); if (activeLink) { activeLink.classList.add('active'); } } function ip_blog_isInViewportThreshold(element, threshold) { var rect = element.getBoundingClientRect(); var windowHeight = window.innerHeight || document.documentElement.clientHeight; var topThreshold = rect.top - threshold; var bottomThreshold = rect.bottom + threshold; return topThreshold <= windowHeight && bottomThreshold >= 0; } window.addEventListener('scroll', ip_blog_setActiveLink); window.addEventListener('load', ip_blog_setActiveLink); }); function ip_blg_findClosestAnchor(element) { while (element) { if (element.tagName === 'A') { return element; } element = element.parentNode; } return null; } function ip_bl_v_scrollToDiv(event_pb, offset) { event_pb.preventDefault(); const ip_bl_linkElement = ip_blg_findClosestAnchor(event_pb.target); if (ip_bl_linkElement) { const it_bl_hashValue = ip_bl_linkElement.getAttribute('href').substring(1); const it_blg_vf_targetElement = document.getElementById(it_bl_hashValue); if (it_blg_vf_targetElement) { jQuery('html, body').animate({ scrollTop: jQuery('#' + it_bl_hashValue).offset().top - offset }, 1000); } } } document.addEventListener('DOMContentLoaded', function() { let it_bl_offset = 0; const ip_blo_vi_anchorLinks = document.querySelectorAll('a[href^="#"]'); ip_blo_vi_anchorLinks.forEach(function(linkip_bg) { linkip_bg.addEventListener('click', function(event_pb) { setTimeout(function() { console.log('Offset passed during click: ' + it_bl_offset); ip_bl_v_scrollToDiv(event_pb, it_bl_offset); }, 0); }); }); });

Table of content

  • Current Date and Time with Datetime in Python
  • Creating Date Objects in Python
  • Strftime() Method: Convert String to Datetime in Python
  • Convert Datetime to String in Python
  • Timestamp to Datetime and vice-versa in Python

Python Date and time Module

See More

There is a Python module that is comprised of various functions to deal, manipulate, and work with dates and date objects. This module is known as the Python datetime module. We can simply start working with dates by importing this module and using the functions and classes it provides.

Current Date and Time with Datetime in Python

Let us see how with the help of the Python datetime module and a simple line of code we can get the current date in Python.

Python Datetime Example:

#import datetime python<br>
import datetime<br>
a = datetime.datetime.now()<br>
print(a)

When the above code block is executed, it will display the current date (containing year, month, day, hour, minute, second, and microsecond in the same order). In the ‘datetime.datetime’ statement, the first datetime is the module and the second one is the datetime class inside of the datetime method which contains information from both date and time objects.

We can also display just one of the attributes of date in python, such as, just the year.

Example:

import datetime<br>
a = datetime.datetime.now()<br>
print(a.year)

Become a Python Expert

Creating Date Objects in Python

In certain cases, we will want to create a custom date instead of just displaying the current date. In those cases, we can use the datetime() class constructor of the Python datetime module.

This Python datetime() class constructor requires three parameters to create a date, that is, year, month, and day.

Example:

import datetime<br>
a = datetime(2050,11,11)<br>
print(a)
Output:<br>
2050-11-11

The Python datetime() class constructor also takes parameters for time and timezone, which are hour, minute, second, microsecond, and tzone. But these parameters are optionally and rarely used. The default value of these parameters is set to 0.

Get 100% Hike!

Master Most in Demand Skills Now!

The strftime() Method: Convert String to Datetime in Python

The datetime module in Python also has a method to convert the date objects into readable strings. So, we can display the month or day in a readable string format instead of numerical representation.

Example:

import datetime<br>
a = datetime.datetime(2020,6,19)<br>
print(a.strftime(“%d”), a.strftime(“%B”))
Output:<br>
19, June

Now, we might be wondering, how do we specify that we want to display the month in a readable string format and what ‘%B’ and ‘%d’ are. Well, Python uses C style formatting to generate new strings. These are called format codes. There are different format codes for different attributes of the date object.

The following table contains a list of all legal format codes and their short descriptions:

Format code Description Example
%a Short version of weekday Wed
%A Full version of weekday Wednesday
%w Weekday as a number starting from 0 to 6, where 0 is Sunday 3
%d Day of the month in numerical format starting from 01 to 31 15
%b Short version of month name Dec
%B Full version of month name December
%m Month as a number starting from 01 to 12 12
%y Short version of a year, i.e., without indicating the century 19
%Y Year in full version 2019
%H Hour in 24-hour format starting from 00 to 23 17
%I Hour in am-pm format; 00–12 05
%p AM/PM PM
%M Minute starting from 00 to 59 41
%S Second starting from 00 to 59 08
%f Microsecond starting from 000000–999999 054647
%Z Timezone CST
%j Day of the year in numerical format, starting from 001 to 366 365
%U Week of the year in numerical format, starting from 00 to 53, where Sunday is the first day of the week 52
%W Week of the year in numerical format, starting from 00 to 53, where Monday is the first day of the week 52
%c Local version of date and time Mon Mar 04 17:41:00 2018
%x Local version of date 03/04/19
%X Local version of time 19:21:00

We can use any of these codes with the strf method to display their respective values. The strftime method can take one or more than one format codes as argument, as shown in our example, where we have used ‘%B’ to display the full version of the month name in a readable string format and ‘%d’ to display the day of the month in a numerical format.

The strptime() Method: Convert Datetime to String in Python

The strptime() method creates a datetime object from the given string.This method takes the string to be converted and the format code as arguments. It’s not possible to create a datetime object from every string. The string has to be in a certain format.

<br>
from datetime import datetime<br>
date_str = "21 June, 2018"<br>
print("Date String =", date_str)<br>
print("Type of Date String =", type(date_str))<br>
date_object = datetime.strptime(date_str, "%d %B, %Y")<br>
print("date_object =", date_object)<br>
print("type of date_object =", type(date_object))
The output will be<br>
Date String = 21 June, 2018<br>
Type of Date String = <class 'str'><br>
date_object = 2018-06-21 00:00:00<br>
type of date_object = <class 'datetime.datetime'><br>

Timestamp to Datetime and vice-versa in Python

A Unix timestamp is the number of seconds between a particular date and January 1, 1970, at UTC.

Python Timestamp to Datetime

Here, we used the datetime.fromtimestamp() classmethod which returns the datetime object. This object is stored in the dt_object variable.

<br>
from datetime import datetime<br>
timestamp = 1545730073<br>
dt_object = datetime.fromtimestamp(timestamp)<br>
print("dt_object =", dt_object)<br>
print("type(dt_object) =", type(dt_object))
The output will be<br>
dt_object = 2018-12-25 09:27:53<br>
type(dt_object) = <class 'datetime.datetime'><br>

Python Datetime to Timestamp

You can get the timestamp from a datetime object using datetime.timestamp() method.

<br>
from datetime import datetime<br>
now = datetime.now()<br>
timestamp = datetime.timestamp(now)<br>
print("timestamp =", timestamp)
The output will be the timestamp for the current datetime.<br>

With this, we come to the end of this module in Python Tutorial. Here we have learned about dealing with dates and time in Python with the help of datetime module. Further, check out our offers for Python training Courses and also refer to the trending Python coding interview questions prepared by the industry experts.

From beginner syntax to pro-level techniques, our Python cheat sheets help you code smarter and faster!

  1. Python Cheat Sheet
  2. Pandas Cheat Sheet
  3. NumPy Cheat Sheet
  4. Scikit-Learn Cheat Sheet
  5. Data Structures with Python Cheat Sheet

 

Related Blogs What’s Inside
What is Pass in Python? Explains the pass statement in Python for reserving empty code spaces.
Init in Python Details the __init__ method for configuring Python class objects.
Python Input and Output Details Python’s input/output features for interactive applications.
What is Data Science in Python? Explores Python’s significance in data science for analytics tasks.
How to Find Length of List in Python Outlines ways to determine the length of lists in Python programming.
Ethical Hacking with Python Describes Python’s applications in ethical hacking for security audits.

About the Author

Lithin Reddy
Lithin Reddy
Data Scientist | Technical Research Analyst - Analytics & Business Intelligence

Lithin Reddy is a Data Scientist and Technical Research Analyst with around 1.5 years of experience, specializing in Python, SQL, system design, and Power BI. Known for building robust, well-structured solutions and contributing clear, practical insights that address real-world development challenges.

Recommended Videos
Python Interview Questions And Answers
Python Interview Questions And Answers
Numpy Interview Questions For Freshers
Numpy Interview Questions For Freshers
Pandas Coding Interview Questions
Pandas Coding Interview Questions
OOPS Interview Questions and Answers
OOPS Interview Questions and Answers
Python Pandas Tutorial
Python Pandas Tutorial
Recommended Programs
Python Course
Python Course
5 (218118)
Free Python Certification Course Online
Free Python Certification Course Online
5 (53455)
Python Data Science Course
Python Data Science Course
5 (76533)
Software Development Engineering Course
Software Development Engineering Course
5 (23421)

Course Preview

Expert-Led No.1

Python Datetime – A Guide to Work With Dates and Times in Python

Intellipaat

facebook twitter linkedin youtube insta telegram

Intellipaat

facebook twitter linkedin youtube insta telegram

Get Our App Now!

Intellipaat android app Intellipaat android app

Get Our App Now!

Intellipaat android app Intellipaat android app

Courses

  • Data Scientist Course
  • Machine Learning Course
  • Python Course
  • Devops Training
  • Business Analyst Certification
  • Cyber Security Courses
  • Business Analytics Training
  • Investment Banking Course
  • SQL Course
  • AWS DevOps Course
  • Full Stack Developer Course
  • Product Management Course

Courses

  • AWS Solutions Architect
  • UI UX Design Course
  • Salesforce Training
  • Selenium Training
  • Artificial Intelligence Course
  • Ethical Hacking Course
  • Azure Administrator Certification
  • Cyber Security Course
  • Digital Marketing Course
  • Electric Vehicle Course
  • Azure DevOps Course
  • Web Development Courses

Tutorials

  • Python Tutorial
  • AWS Tutorial
  • Devops Tutorial
  • Java Tutorial
  • Node Js Tutorial
  • Cyber Security Tutorial
  • Salesforce Tutorial
  • Azure Tutorial
  • Ethical Hacking Tutorial
  • Data Science Tutorial
  • Cloud Computing Courses
  • Python Data Science Course

Interview Questions

  • Python Interview Questions
  • AWS Interview Questions
  • Data Science Interview Questions
  • Devops Interview Questions
  • Salesforce Interview Questions
  • Java Interview Questions
  • SQL Interview Questions
  • React Interview Questions
  • Node Js Interview Questions
  • Digital Marketing Interview Questions

Browse By Domains

Data Science Salesforce Courses Cloud Computing Courses AI & Machine Learning Courses Project Management Courses Cyber Security and Ethical Hacking Courses Web Development Courses Job Oriented Courses Degree Courses Marketing CRM Courses Software Development Courses Doctorate Programs Undergraduate Courses Banking and Finance Courses Product Design Courses Electric and Hybrid Vehicle Courses Leadership & Management Courses Management Courses Generative AI Courses Design Thinking Courses Microsoft Certification Courses

Top Tutorials

Machine Learning Tutorial Power BI Tutorial SQL Tutorial Artificial Intelligence Tutorial Digital Marketing Tutorial Data Analytics Tutorial UI/UX Tutorial

Top Articles

Cloud Computing Data Science Machine Learning What is AWS Digital Marketing Cyber Security Salesforce Artificial Intelligence

Top Interview Questions

Selenium Interview Questions Azure Interview Questions Machine Learning Interview Questions Cyber Security Interview Questions Business Analyst Interview Questions and Answers C Interview Questions Data Analyst Interview Questions Software Engineering Interview Questions

© Copyright 2011 - 2026 Intellipaat Software Solutions Pvt. Ltd.
Media
Contact Us
Tutorials
Interview Questions

Address: 6th Floor, Primeco Towers, Arekere Gate Junction, Bannerghatta Main Road, Bengaluru, Karnataka 560076, India.

Disclaimer: The certification names are the trademarks of their respective owners.

INTPL_2026-05-22