Date and Time in Python programming | Hands on coding

By using datetime, date and time module we can get current date and time in very simple way.

There are many way to print data and time in python i am trying to explain in simple way.

Print current Date

  • By using today() method of class date we can print the current date.

Method 1
#import module
import datetime
#Fetching current date
date_obj = datetime.date.today()
print("Current date:",date_obj)
"""
***Output***
Current date: 2020-05-06
"""
 
  • Here datetime is a module,date is a class and today() is method which is defined inside class date.

Method 2
from datetime import date
today_date = date.today()
print("Current date :", today_date)
"""
***Output***
Current date: 2020-05-06
""" 

Print current year, month and day


from datetime import date
#creating object
today_date = date.today()
print("Current Year :", today_date.year)
print("Current Month :", today_date.month)
print("Current Date :", today_date.day)
"""
***Output***
Current Year : 2020
Current Month : 5
Current Date : 6
"""
 

Print current time method 1

  • By using datetime object we can also print current time.

Example 1
from datetime import datetime
now = datetime.now()
print("Current Date and Time:",now)
#extracting time
current_timeObj = now.strftime("%H:%M:%S")
print("Current Time =", current_timeObj)
"""
***Output***
Current Date and Time: 2020-05-06 13:56:52.214912
Current Time = 13:56:52
"""
  • Here now() function returns current date and time.
  • We can also create object of time for better understanding see the example:

Method 2
from datetime import datetime
#creating  time object
now = datetime.now().time()
print("Current Time :", now)
"""
***Output***
Current Time : 14:01:13.173288
"""

Print current time method 2

  • We can also print the current time using time module.

import time
#creating object
t = time.localtime()
#extracting current time
current_time = time.strftime("%H:%M:%S", t)
print("Current Time :", current_time)
"""
***Output***
Current Time : 14:07:47
"""

Print current Date and Time

  • By using datetime module we can print data and time.
  • Here now() is a method of class datetime that returns current date and time.

import datetime
datetime_obj = datetime.datetime.now()
print("Current Date and Time:",datetime_obj)
"""
***Output***
2020-05-06 13:53:21.854965
"""