To get current or today's date and time in Python, we can use either date or datetime class. Python provides both classes to deal with date & date time. Python date and datetime class both belongs to datetime module. To deal with date and time, we must import datetime module first.
In this example, we are getting current date and time by using now() method of datetime class.
from datetime import datetime
# fetch current date and time
current_datentime = datetime.now()
print("Current date and time : ",current_datentime)
Output:
Current date and time : 2020-04-01 21:47:38.247574
In case, we want current time only then we can use time() method of datetime class. It returns current time including miliseconds.
from datetime import datetime
# fetch current time only
current_time = datetime.now().time()
print("Current time : ",current_time)
Output:
Current time : 22:06:33.010615
To get today's date, use date() method with now() method. It will return date only. See the below example.
from datetime import datetime
# fetch current date only
current_date = datetime.now().date()
print("Current date : ",current_date)
Output:
Current date : 2020-04-01
In case, if we want to get today's date without using now() method then we can use date() method of date class. To use date() method, we need to import date class first. See the below example.
from datetime import date
# fetch today date only
today_date = date.today()
print("Today date : ",today_date)
Output:
Today date : 2020-04-01
In this tutorial, we learnt about how to get today's date and current time using Python datetime module. In the next chapter, we will discuss about how to change date format and apply other advance date time methods as well. Till then Happy Coding!