The datetime module is in the standard library. It holds the classes for dates and times.

A date is an object, like everything else in Python. There is a class for a plain date, one for a date with a time, and one for a gap between two moments.

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 Code Meanining
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal ‘%’ character.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.