Datetime Module in Python

Module - 8 Python Libraries and Advanced Concepts
Datetime Module in Python


Python has a DateTime module for working with dates and timings. DateTime is an intrinsic module in Python rather than a basic data type; we only need to import the module stated above to interact with dates as date objects.

Introduction to Python Datetime

Python Datetime could be a module that permits for the control of datetime objects. It contains capacities and classes for working with dates, times, and timezones. It can be utilized to change over strings to datetime objects, compare dates and times, and control the yield of dates and times in different groups. Python Datetime too gives tools for working with timezones, performing arithmetic operations with dates, and making calendars.

How to Use Date and Datetime Class?

The datetime module of Python offers various useful classes for effortlessly manipulating and processing dates and times. This module contains classes that can represent dates and times in a datetime object, allowing Python programmers to easily extract components of dates such as years, months, days, hours, minutes, and seconds. The datetime module additionally allows for simple date arithmetic and formatting date strings into standard formats. By utilizing the datetime module, Python developers can efficiently handle date and time information in their programs without having to manually parse and calculate dates and times. The datetime module greatly simplifies the process of working with dates and times in Python applications.

Date: The date class of the datetime module is used to store and manipulate dates.


import datetime

# Create a date object
d =, 7, 15)

# Get the year, month, and day of the date
year = d.year
month = d.month
day =

# Get the weekday number for the date
weekday = d.weekday()

# Get today's date
today =

This code imports the datetime module and creates a date object. It then retrieves the year, month, and day of the date, as well as the weekday number for the date. Finally, it retrieves today's date.

Datetime: The datetime class of the datetime module is used to store and manipulate date and time.

import datetime

# Create a datetime object
dt = datetime.datetime(2020, 7, 15, 12, 30, 45)

# Get the year, month, day, hour, minute, and second of the datetime
year = dt.year
month = dt.month
day =
hour = dt.hour
minute = dt.minute
second = dt.second

# Get today's datetime
today =

This code imports the datetime module and creates a datetime object. It then retrieves the year, month, day, hour, minute, and second of the datetime. Finally, it retrieves today's datetime.

Classes of DateTime Python Module

  1. The date data type stores calendar date information, including the year, month, and day. It allows you to represent a specific date on the calendar.
  2. The time data type stores the time of day, including the hour, minute, second, and microsecond. It allows you to represent a specific point in time each day.
  3. The datetime data type combines the date and time data types to store both calendar date and time of day information together. It allows you to represent a full timestamp, specifying both when something happened and what day it occurred on.
  4. The timedelta data type is used to compute the difference between two dates, times, or datetimes. It allows you to calculate the amount of time between two points in time so you can determine how much time has passed or how much time remains until a future date.
  5. The tzinfo data type is used to store timezone information. It allows you to specify the timezone for a particular date, time, or datetime value so you know the local time represented and can correctly handle daylight saving time and other timezone-related adjustments.


import datetime
# Get current date and time
now =
# Get date from now
date =
# Get time from now
time = now.time()
# Get datetime from now
datetime_now = now.datetime()
# Find difference between two datetimes
difference = - datetime.datetime(2017, 7, 1)
# Create a timezone aware datetime
tz_aware_datetime = datetime.datetime(2017, 7, 1, tzinfo=datetime.timezone.utc)

This code imports the datetime module, which allows us to access various types of date and time objects. The code then gets the current date and time and assigns it to the now variable. It then uses the now variable to get the date, time, and datetime, which are all stored in separate variables. It also calculates the difference between two datetimes using the subtraction operator. Finally, it creates a timezone aware datetime, which is assigned to the tz_aware_datetime variable.

Basics of pytz Library

The pytz library may be a library for Python that gives access to the Olson timezone database. It permits clients to get to and utilize time zone data from Python. It gives a way to change over neighborhood times to other time zones and work with timezone-aware datetime objects. It too gives a list of timezone names and their comparing UTC offsets. The pytz library is valuable for applications that got to be mindful of diverse timezones, such as for planning occasions or for internationalization.

The syntax for creating a timezone in Python with the pytz library is as follows:

import pytz
timezone = pytz.timezone('<timezone name>')

The ‘timezone name’ should be replaced with a valid Olson tz database name, such as 'America/New_York' or 'Europe/London'.

Date Class

  1. .today(): This function returns the current local date.
  2. .min(): This function returns the minimum value of the given data.
  3. .max(): This function returns the maximum value of the given data.
  4. .day(): This function returns the current day as an integer.
  5. .month(): This function returns the current month as an integer.
  6. .year(): This function returns the current year as an integer.
  7. .strftime(): This function formats the date and time in a specified format.

Current date

These are the ways to find the current date

  1. .today()
  2. .now()

The .today() method from the datetime module returns the current local date. It returns a datetime object without time information.

The .now() method from the datetime module returns the current local date and time. It returns a datetime object with time information.

Use of datetime.strptime()

The datetime.strptime() strategy is utilized in Python to change over a string to a datetime object. This strategy takes in two arguments, the string to be changed over and the format of the string. It parses the string to create a datetime object which can at that point be utilized for different operations. This method is particularly valuable when managing with a huge number of date designs from different sources.

import datetime

dt_str = '2021-02-03 10:45:30'
dt_obj = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')


# Output: 2021-02-03 10:45:30

In the above illustration, we have imported the datetime module and made a string variable dt_str that contains a date-time string. We at that point utilized the datetime.strptime() method to change over the string to a datetime object. The first argument of the method is the string to be changed over and the second argument is the format of the string. In this case, the arrange is '%Y-%m-%d %H:%M:%S' which matches the format of the string. The resulting datetime object is at that point printed to the console.

How to Get Current timeStamp?

import datetime

current_timestamp =


This code imports the datetime module and uses it to get the current timestamp (in seconds since the epoch). It then prints out the timestamp.

How to Know the Day of the Given Date?

To know the day of the given date in Python, you can use the datetime library.

For example, if you have a date in the format of YYYY-MM-DD, you can use the following code to find the day:

import datetime

date = '2020-08-22'

date_object = datetime.datetime.strptime(date, '%Y-%m-%d')

day = date_object.strftime('%A')


# Output: Saturday

Generate a List of Dates from a Given Date

import datetime

# Generate a list of dates from today + 5 days
start_date =
end_date = start_date + datetime.timedelta(days=5)
date_range = [start_date + datetime.timedelta(days=x) for x in range(0, (end_date-start_date).days)]


This code creates a list of dates between a start date (in this case, the current date) and an end date (in this case, 5 days from the start date). It does this by creating a date range starting at 0 days from the start date and ending at the number of days between the start date and the end date. Each day is then added to the date range as a datetime object. The result is a list of dates in the range.

Applications Of Python DateTime Module

  1. Database applications: Python's datetime module can be utilized to store and recover date and time information from databases.
  2. Automated scheduling: The datetime module can be utilized to plan mechanized errands, such as sending mail updates or running normal reports.
  3. Web applications: The datetime module can be utilized to arrange dates and times for show on websites.
  4. Information examination: The datetime module can be utilized to analyze time-series information, such as stock advertise execution over time.
  5. Information visualization: The datetime module can be utilized to form charts and charts that visualize changes in information over time.


Python's DateTime module offers different classes for effectively taking care of and controlling dates and times. The module contains classes for dates, times, date-times, timedeltas, and timezones. The date course is utilized to store and control dates, whereas the datetime course is utilized for putting away date and time data. With these instruments, Python designers can effectively handle and control date and time data in their programs.

Key takeaways

  1. The datetime module gives a run of classes for controlling and designing dates and times in Python.
  2. The function returns the current date and time in neighborhood time.
  3. The function returns the date object from a string or timestamp.
  4. The datetime.timedelta() function returns the contrast between two datetime objects.
  5. The datetime.strftime() strategy groups a datetime protest into a string.
  6. The datetime.strptime() strategy parses a string into a datetime question.
  7. The datetime.strptime() strategy is valuable for changing over strings into datetime objects.
  8. The datetime.timezone() function makes a timezone object.
  9. The datetime.timetz() function returns a timezone mindful datetime protest.
  10. The datetime.utcnow() function returns the current date and time in UTC time.


  1. Which of the following is used to represent the current date?
    4. datetime.time()


  1. What is the format of the date returned by strftime()?  
    1. YYYYMMDD 
    2. DDMMYYYY 
    3. YYYY-MM-DD 
    4. DD-MM-YYYY

Answer:d. DD-MM-YYYY

  1. What is the function used to convert a string to a datetime object?
    1. datetime.strptime()  
    2. datetime.strftime() 
    4. datetime.time()

Answer:a. datetime.strptime()

  1. How can you calculate the difference between two dates? 
    1. datetime.diff() 
    3. datetime.subtract()  
    4. datetime.timedelta()

Answer:d. datetime.timedelta()

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter