How to get date and time in Python

Python has a module called as datetime which gives the current date and time in Python. Datetime module comes with pre-built so we dont have to install it explicitly but we do need to import the module. datetime module provide some functions to get the current date as well as time. You can get complete information from the document website here. In this article, we will look at the some of the important functions and implement with examples. Let’s look at them.

date.today():
today() method of date class under datetime module returns a date object which contains the value of Today’s date.

Syntax: date.today()
Returns: Return the current local date.

Implementation of datetime

# Import the module datetime
import datetime as dt

# Returns the current local date using class date
today_date = dt.date.today()
print("Today's date: ", today_date)
# We can extract date, month and year separately too
print("Today's date: ", today_date.day,"-",today_date.month,"-",today_date.year)

To know what is inside datetime, we can use dir() function to get a list containing all attributes of a module.

import datetime
print(dir(datetime))

Output:

['MAXYEAR', 'MINYEAR', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

We have already seen the date class. Other commonly used classes are: time, datetime, timedelta

We can create object of Time class to represent time. example:

from datetime import time
import datetime as dt
from time import strftime

current_time = dt.datetime.now()
print("current_time =", current_time.time())
#change the format
print(dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

# time(hour, minute and second)
time1 = time(11, 34, 56)
print("Given time =", time1)

time2 = time(hour = 11, minute = 34, second = 56)
print("Given time =", time2)

# time(hour, minute, second, microsecond)
time3 = time(11, 34, 56, 234566)
print("Given time =", time3)