Ad Code

Responsive Advertisement

Date-Time Module in Python

Date-Time Module in Python


In this tutorial, you will learn how to manipulate date and time in Python with Examples.


Python has the standard library which contains the Modules, Modules contain class, Class contain functions which contain method.

Let us take a Real-life  Example to understand it better 

For Example 

In a Real-life Library, we have lots of books to read.

Here Library contains Books and Books contains chapters and chapters contains Content.

So here Library is the Standard Library, Books are the Modules, Chapters are the functions, Contents are the Methods.

So let us get started with the Date-Time Module-:

What is Date-time Module in Python?


Date-Time Module is the Module in Python Which is used to Manipulate Date and Time.

How to use Date-Time Module?


To use date-time Module, we have to import this module using syntax - 
 import datetime

See the Example -:

import datetime
date_time=datetime.datetime.now()
print("Todays date and time is",date_time)


Here we have imported datetime module which contains datetime class and this class contains now()method which is used to get the current time.


When you  run this program output will be like this-:

 Todays date and time is 2020-05-26 10:35:23.582899



Example To get the Current date


import datetime
date_today=datetime.date.today()
print("Todays date and time is",date_today)

Here today() is used to get today's date.

Its Output will be like this -:

 Today's date is 2020-05-26

Example to get the Year, Month and Date


import datetime
date=datetime.datetime.today()
print("Current Years is",date.year)
print("Current Month is ",date.month)
print("Todays date is ",date.day)

  • date.year is used to get the current Year.
  • date.month is used to get the current Month.
  • date.day is used to get today's date.


Output -: 


Current year is 2020
Current month is 5
Today's date is 26


Example to Get the Week-Day


import datetime
date=datetime.datetime.today()
print("Current Week_day is",date.weekday())


Here Weekday() is used to get the weekday.

Output-:

Current Week_day is 1


Example to Get the Hour, Minute, and Second


import datetime
time = datetime.datetime.today()
print("Current Hour is ",time.hour)
print("Current Minute is " , time.minute)
print("Current second is " , time.second)


Here

  • time.hour is used to get the current hour.
  • time.minute is used to get the current minute.
  • time.second is used to get the current second.


Output-:

Current Hour is 11
Current minute is 5
Current second is 7



:::  For any Query Comment Below :::