Return Actual Date and Time in Python (4 Examples)

In this tutorial, I’ll demonstrate how to show the current date & time in the Python programming language.

Example 1: Show Current Date and Time

For this first example, we need to load the following module:

from datetime import datetime                 # Import library

The datetime.now function returns us a datetime object with both information: date and time.

datetime_x = datetime.now()                   # datetime.now function
print(datetime_x)
# 2022-06-09 11:15:52.100892

Example 2: Get Actual Local Date

If we just want to get the current date, there are several options, I’ll show you in three different examples.

All of them rely on the following module we first have to load:

from datetime import date                     # import date class to Python

This example uses the date.today function to return the actual date without the time component:

my_date_x = date.today()                      # Creating example date
print(my_date_x)
# 2022-06-09

Example 3: Actual Date in Another Format (dd/mm/YY)

If we want the output in another structure, we can add the strftime function with format codes:

my_date_2 = my_date_x.strftime("%d/%m/%Y")    # Apply strftime function
print(my_date_2)
# 09/06/2022

Example 4: Actual Date in Different Format (Month abbreviation, day and year)

There are many options to change the output of the function to get the format you want:

my_date_3 = my_date_x.strftime("%b-%d-%Y")    # Using strftime function
print(my_date_3)
# Jun-09-2022

Here you can find a summary of different date and time format codes.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top