13 Examples to Learn Python datetime module in 30 Minutes

Python datetime module

Python comes up with a few date and time modules. One of those is the datetime module. In order to format the date and time in your programs, you have to import the datetime module into your programs.

We have Video of this tutorial


This is how you may include the datetime Python module in your program:

Importing datetime module:

import datetime

Python date and time formatting examples

Following are a few date and time formatting examples in Python. We will use the datetime properties to format the date and time. See examples with the code below.

An example of  current time and date

The following example will return the current date and time by using the datetime module. The daytime’s now method is used to return the current time and date.

Getting current day example

Following example uses the datetime.date to return the current day. Note that, the strftime is the string representation of the date, used in the examples below.

Also, the output shown in the example pages is related to the dates when these demo pages were created.

Getting current month number example

You may embed the ‘%m’ directive to get the current month number. For example, 03 for March.

Getting current month name with full month name

To get full the month name like October, November etc. use the %B directive.

Getting current month abbreviation

For the abbreviation of the Month name like Sep, Oct, Dec etc. use the ‘%b’ in the formatted string.

Getting Current year in Python

See this example where the current Year is displayed by using the datetime module:

Note: Use the ‘%y’ to get the year in two digits.

Number of day of the Week

For getting the number of the day in a Week, use the %w. In that case, the 1 is for Monday, 2 for Tuesday and so on.

Getting name of the day

You can use ‘%A’ directive to get the name of the day like Monday, Tuesday, Wednesday etc. as shown in the example below:

Current date in dd/mm/yyyy example

The following example uses Python datetime module to display the current date in dd/mm/yyyy format.

Format date in day name and month name example

Python Current time example (hh: mm :ss)

Following example displays the current time using datetime module.

Display week number of the year

For getting the number of Week in the year, use the %U as shown in the code below:

Display current date

Display the current date by using the ‘%x’:

Further Reading: The Python time Module


Was this article helpful?

Related Articles

Leave A Comment?