Strftime() Method Of Time Class In Python

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:

# ----- 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:

Time in 24 hour format:13:30:15

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

 

Example 2:

# ----- 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:

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


Copyright 2024 © pythontic.com