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:

Full weekday name example

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

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:

Display current full month name example

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

Display current month as number

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

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.

Python current hour in 24 hours format

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

Display current hour as 12 hours clock

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

Display weekday of the Week in number

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

1= Monday

0 = Sunday

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.

Python current time

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

Display year without century

Display year with century

Display time zone

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

Was this article helpful?

Related Articles

Leave A Comment?