How to get current date and time in Python?

In this article, you will learn to get today's date and current date and time in Python. We will also format the date and time in different formats using strftime() method.

There are a number of ways you can take to get current date. We will use date class of the datetime module to accomplish this task.


Example 1: Python get today's date


from datetime import date

today = date.today()
print("Today's date:", today)

Here, we imported date class from the datetime module. Then, we used date.today() method to get the current local date.

By the way, today variable will be a date object. You can use strftime() method to create string representing date in different formats from this object.


Example 2: Current date in different formats


from datetime import date

today = date.today()

# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)

# Textual month, day and year	
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)

# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)

# Month abbreviation, day and year	
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d3)

When you run the program, the output will be something like:


d1 = 25/12/2018
d2 = December 25, 2018
d3 = 12/25/18
d4 = 12/25/18

If you need to get current date and time, you can use datetime class of the datetime module.

Example 3: Get current date and time


from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)	

Here, we have used datetime.now() to get current date and time. Then, we used strftime() method to create a string representing date and time in another format.