To print the current date, we can utilize the datetime module. Dates are objects, like anything in Python. Datetime has several subclasses, which can be confusing at first.

Related course:

Date Example

We can use its method strftime() to change the format.
To show the current date (today):

import datetime
today = datetime.date.today()
print(today)

This will show the date in the format

YYYY-MM-DD

If you want another format, use the method strftime():
import datetime
today = datetime.date.today().strftime("%d-%m-%Y")
print(today)
This will output

DD-MM-YYYY

Get current time in Python

You can get the current time like this:

import datetime
currentTime = datetime.datetime.now().time()
print(currentTime)

To get the date and time, use:

import datetime
currentTime = datetime.datetime.now()
print(currentTime)

python datetime get current time and date

Format codes

When using the method strftime() we can specify the type of date format we want to show.

So which format codes do we have?

Format CodeMeanining
%aLocale’s abbreviated weekday name.
%ALocale’s full weekday name.
%bLocale’s abbreviated month name.
%BLocale’s full month name.
%cLocale’s appropriate date and time representation.
%dDay of the month as a decimal number [01,31].
%fMicrosecond as a decimal number [0,999999], zero-padded on the left
%HHour (24-hour clock) as a decimal number [00,23].
%IHour (12-hour clock) as a decimal number [01,12].
%jDay of the year as a decimal number [001,366].
%mMonth as a decimal number [01,12].
%MMinute as a decimal number [00,59].
%pLocale’s equivalent of either AM or PM.
%SSecond as a decimal number [00,61].
%UWeek number of the year (Sunday as the first day of the week)
%wWeekday as a decimal number [0(Sunday),6].
%WWeek number of the year (Monday as the first day of the week)
%xLocale’s appropriate date representation.
%XLocale’s appropriate time representation.
%yYear without century as a decimal number [00,99].
%YYear with century as a decimal number.
%zUTC offset in the form +HHMM or -HHMM.
%ZTime zone name (empty string if the object is naive).
%%A literal ‘%’ character.