Python time module with 14 examples

The time module in Python

The time module of Python is used to format date and time. In order to use the time module in Python programs, this has to be included. This chapter explains how to use Python time module but let us first look at how you can import it.

This is how you will import the time module into Python project:

Import time

General syntax of using time module

time.strftime(format)

Where Format is the directive you can use like %c, %a, %A etc.

Examples of time and date formatting using time, Python module are given below.

Formatting date and time examples

Following are examples using time module with formatting characters to display formatted date and time. Note that, for our examples we are using 12/01/2013 date.

Current time and date with %c example

To get the current time and date you can use ‘%c’ directive as follows:

See this example online


Full weekday name example

To get the full Weekday name like Sunday, Monday etc. use the ‘%A’ formatting character.

See this example online


Display current short month name

If you need to display the month in short format like Jan, Feb, Mar etc. then use the ‘%b’ directive, as shown in the example below:

See this example online


Display current full month name example

To get the full Month name you can use ‘%B’. See example:

See this example online


Display current month as number

Small letter i.e. ‘m’ is used to return the current month in Python time module. See example below.

See this example online


Display current day of month as number example

Following example uses the time module to display the current day of the month as a number.

See this example online


Python current hour in 24 hours format

Use ‘%H’ to get the current hour in 24-hour clock format.

See this example online


Display current hour as 12 hours clock

This example uses time with ‘%I’ to return current hour in 12 hours format.

See this example online


Display weekday of the Week in number

To get the number of day in the Week, use ‘%w’, Where:

1= Monday

0 = Sunday

See this example online


Display current date

To get and display only the current date, unlike in above example where we displayed the date and time, use the ‘%x’ directive.

See this example online


Python current time

Following example returns the current time using by using the ‘%X’.

See this example online


Display year without century

See this example online


Display year with century

See this example online


Display time zone

Following example returns timezone using ‘%z’ with the time module.

See this example online


Was this article helpful?

Related Articles

Leave A Comment?