strftime() Method Of Time Class In Python

strftime() function of datetime.time class returns a formatted string of a time object. Hours, minutes, seconds, microseconds, time zone information components can be controlled through the format string. The Python examples print the AM/PM, 24 hour formats and time zone details of time instances.

Time Updated 15 Jul 2019 1 min read

Function Name

strftime

Function Signature

strftime(format)

Parameters

format – The format string specifying various time components expected in the return value.

Return Value

Returns the formatted time string.

Overview

  • The method strftime() of datetime.time class in Python, converts a time object into a Python string based on the format string provided.
  • Hours, minutes, seconds, microseconds and timezone components of the output time string can be controlled through the strftime() method.

Example 1

python
# ----- Example Python Program printing formatted time using strftime() -----

import datetime

# Create a time instance...independent of any day

timeObject      = datetime.time(13, 30, 15, 10);

# Print in 24 hour format

formattedTime   = timeObject.strftime("%H:%M:%S");

print("Time in 24 hour format:%s"%formattedTime);

# Print in AM/PM format

formattedTime   = timeObject.strftime("%I:%M:%S %p");

print("Time in AM/PM format:%s"%formattedTime);

Output

Output
Time in 24 hour format:13:30:15

Time in AM/PM format:01:30:15 PM

Example 2

python
# ----- Example Python Program printing formatted time with timezone using strftime() -----

import datetime

estOffset   = datetime.timedelta(hours= -5);

estTimeZone = datetime.timezone(offset=estOffset);

# Time object with timezone as EST

timeWithTz      = datetime.time(13, 30, 15, 10, tzinfo=estTimeZone);

# Print with timezone info

timestring   = timeWithTz.strftime("%H:%M:%S %z");

print("Time with time zone information:%s"%timeWithTz);

Output

Output
Time with time zone information:13:30:15.000010-05:00