Beginner Level
Intermediate Level
Advanced Level
Introduction
The python programming language is widely used in various industries, including finance, healthcare, and technology, among others. One of the essential modules in python is the Datetime module, which provides developers with a powerful set of tools to manipulate date and time information. In this tutorial, we will explore the Datetime module in python and show you the various ways you can work with date and time data types.
Table of Contents :
- Datetime module in Python
- Datetime Class
- Getting Current Date and Time
- Creating a Datetime Object
- Formatting a Datetime Object
- Converting a String to a Datetime Object
- Working with Time Intervals
- find difference between two dates
- add a time duration to
datetime
object.
- Working with Timezones
- Different Classes of datetime module in Python
- datetime.date class.
- datetime.time class.
- datetime.datetime class.
- datetime.timedelta class.
- datetime.tzinfo class
- datetime.timezone class
Datetime module in Python
- Python's
datetime
module provides a number of ways to manipulate dates and times. - The
datetime
module in Python is a module that is used to work with- dates,
- times, and
- time intervals.
- It provides various classes, methods, and functions to work with date and time.
- The
datetime
module exports four types:- date : date objects represent a date (day, month, and year) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.
- time : time objects represent a time (hour, minute, second, sub-second) on an idealized clock.
- datetime : datetime objects combine both date and time information into a single object.
- timedelta : timedelta objects represent the difference between two datetime objects.
Datetime Class
- The
datetime
module contains the class with same name i.e.datetime
. - The
datetime
class is the main class in thedatetime
module. - It is used to represent dates and times.
- This name clash between the module and the class can be a little confusing. One need to be careful while using the import statement.
- We can access the
datetime
class in two ways. - The first method is by using the dot operator :
- We can import only the
datetime
module using the code :import datetime
- Then we can access the
datetime
class using dot operator :datetime.datetime
- Code sample : The code sample below imports the
datetime
module and then accesses thedatetime
class using the dot operator.
- We can import only the
# importing the module
import datetime
# Accessing datetime class
dt = datetime.datetime
print(dt.now())
- Second method of accessing the
datetime
class is by importing it in import statement.- To import The
datetime
class from the module we need to write :from datetime import datetime
- Code Sample :
- To import The
# importing the class
from datetime import datetime
# Using datetime class
dt = datetime.now()
print(dt)
Getting Current Date and Time
- The
datetime
class has a method callednow()
which returns the current date and time. - The
datetime
class also has methods to get the current year, month, day, hour, minute, second, and microsecond.
from datetime import datetime
# Get the current date and time
now = datetime.now()
print(now)
print()
# Print the current year, month, day, hour, minute, second, and microsecond
print(f"Current Year : {now.year}, \n"
f"Current Month : {now.month}, \n"
f"Current Day : {now.day}, \n"
f"Current Hour : {now.hour}, \n"
f"Current Minute : {now.minute},\n"
f"Current Second : {now.second}, \n"
f"Current microsecond : {now.microsecond}")
Creating a Datetime Object
- We can create a
datetime
object using thedatetime
class constructor. - The constructor takes arguments for year, month, day, hour, minute, second, and microsecond.
- The
datetime
object is actually a date with year, month, day, hour, minute, second, and microsecond components. - If we omit the hour, minute, second, and microsecond arguments they take the default value of zero.
- The year, month, day arguments are mandatory.
- Code Sample :
import datetime
# Creating a datetime object
dt = datetime.datetime(2011, 4, 12, 10, 20, 0, 44)
# Printing the datetime object
print("datetime object = ", dt)
print()
# Print the year, month, day, hour, minute, second, and microsecond of the date
print(f"Year : {dt.year}, \n"
f"Month : {dt.month}, \n"
f"Day : {dt.day}, \n"
f"Hour : {dt.hour}, \n"
f"Minute : {dt.minute},\n"
f"Second : {dt.second}, \n"
f"microsecond : {dt.microsecond}")
# Output
# datetime object = 2009-04-12 10:20:00.000044
# Year : 2011,
# Month : 4,
# Day : 12,
# Hour : 10,
# Minute : 20,
# Second : 0,
# microsecond : 44
Formatting a Datetime Object :
- The
strftime()
method is used to format adatetime
object. - It takes a format string as an argument and returns the
datetime
object as a formatted string. - The format string uses some format codes that indicates what should be the format of the output string.
- Our next tutorial deals with strftime() method in detail and contains a full list of format codes that we can use.
- Code Sample :
import datetime
# Creating a datetime object
dt = datetime.datetime(2015, 10, 25, 10, 30, 0)
# Formatting the datetime object
formatted_date = dt.strftime("%A, %d %B %Y %I:%M:%S %p")
print(formatted_date)
# Output
# Sunday, 25 October 2015 10:30:00 AM
Converting a String to a Datetime Object :
- The
strptime()
method is used to convert a string to adatetime
object. - It takes the string and the format string as arguments and returns a
datetime
object. - Our tutorial on strptime() method discusses this method in detail.
- Code Sample :
from datetime import datetime
# Convert a string to a datetime object
dt_string = "2015-10-25 10:30:00"
dt_object = datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
# Print the datetime object
print(dt_object)
# Output
# 2015-10-25 10:30:00
Working with Time Intervals :
- The
timedelta
class of thedatetime
module is used to represent time duration. - We can use
timedelta
to represent time duration in form of days, hours, minutes, seconds, and microseconds. - We can import the
timedelta
class by using the construct :from datetime import timedelta
- The
timedelta
class can be used to perform arithmetic on dates and times. - In this section, we present a couple of methods of performing timedelta arithmetic.
- We have a detailed tutorial on timedelta class which discusses many other ways in which we can do arithmetic with timedelta objects.
Find difference between two dates
- We can find the difference between two dates using the subtraction operator to get a
timedelta
object. - Code Sample :
from datetime import date
d1 = date(2017, 5, 19)
d2 = date(2017, 5, 15)
# Getting the difference between two dates
diff = d1 - d2
print("Time Diff :", diff)
print("Data type of diff : ", type(diff))
print()
# Output
# Time Diff : 4 days, 0:00:00
# Data type of diff : <class 'datetime.timedelta'>
Add a time duration to datetime object
- We can add a time duration to a
datetime
object usingtimedelta
to get a newdatetime
object. - Code sample :
from datetime import datetime
from datetime import timedelta
# Adding a time duration to a datetime object
dt = datetime(2017, 5, 9)
new_date = dt + timedelta(days=7)
print("Orig. date :", dt)
print("New date :", new_date)
print("Data type of New date :", type(new_date))
print()
# Output
# Orig. date : 2017-05-09 00:00:00
# New date : 2017-05-16 00:00:00
# Data type of New date : <class 'datetime.datetime'>
Working with Timezones
- The
pytz
module can be used to work with timezones. - It provides classes to represent timezones and to convert between timezones.
- The code sample below shows how we can use the
pytz
module in python. - Our tutorial on timezones discusses timezones in python in detail.
- Code Sample :
import datetime
import pytz
utc_time = datetime.datetime(2017, 5, 9)
utc_zone = pytz.utc
local_zone = pytz.timezone('Asia/Kolkata')
local_time = utc_time.astimezone(local_zone)
print(local_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# Output
# 2017-05-09 00:00:00 IST+0530
Different Classes of datetime module in Python :
- The datetime module consists of a number of functions and classes for manipulating dates and times.
- Below are the classes contained in the datetime module :
- datetime.date class.
- datetime.time class.
- datetime.datetime class.
- datetime.timedelta class.
- datetime.tzinfo class
- datetime.timezone class
datetime.date class :
- The datetime.date class represents a date object.
- The datetime.date class has the following methods:
- datetime.date.today()
- datetime.date.fromtimestamp()
- datetime.date.fromordinal()
- datetime.date.weekday()
- datetime.date.isoweekday()
- datetime.date.isocalendar()
- datetime.date.isoformat()
- datetime.date.strftime()
- datetime.date.__str__()
datetime.time class :
- The datetime.time class represents a time object.
- The datetime.time class has the following methods:
- datetime.time.hour
- datetime.time.minute
- datetime.time.second
- datetime.time.microsecond
- datetime.time.tzinfo
- datetime.time.isoformat()
- datetime.time.strftime()
- datetime.time.__str__()
datetime.datetime class :
- The datetime.datetime class represents a datetime object.
- The datetime.datetime class has the following methods:
- datetime.datetime.today()
- datetime.datetime.now()
- datetime.datetime.utcnow()
- datetime.datetime.fromtimestamp()
- datetime.datetime.utcfromtimestamp()
- datetime.datetime.fromordinal()
- datetime.datetime.combine()
- datetime.datetime.date()
- datetime.datetime.time()
- datetime.datetime.timetz()
- datetime.datetime.astimezone()
- datetime.datetime.replace()
- datetime.datetime.strptime()
- datetime.datetime.isoformat()
- datetime.datetime.strftime()
- datetime.datetime.__str__()
datetime.timedelta class :
- The datetime.timedelta class represents the difference between two datetime objects.
- The datetime.timedelta class has the following methods:
- datetime.timedelta.days
- datetime.timedelta.seconds
- datetime.timedelta.microseconds
- datetime.timedelta.total_seconds()
- datetime.timedelta.__str__()
datetime.tzinfo class :
- The datetime.tzinfo class is an abstract base class for time zone information objects.
- These objects provide methods for converting datetime objects from one time zone to another.
- It is an abstract base class for time zone objects.
datetime.timezone class
- datetime.timezone class implements the
tzinfo
abstract base class as a fixed offset from the UTC.
Prev. Tutorial : module Vs package
Next Tutorial : Using datetime.strftime()