Python datetime.strftime()

Python strftime() function

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.

Syntax :

 
strftime(format)

Returns : It returns the string representation of the date or time object.

List of format codes : Reference table for the format codes.

Example:

 # Python program to demonstrate
# strftime() function
  
  
fromdatetime importdatetime as dt
  
# Getting current date and time
now =dt.now()
print("Without formatting", now)
  
# Example 1
s =now.strftime("%a %m %y")
print('\nExample 1:', s)
  
# Example 2
s =now.strftime("%A %-m %Y")
print('\nExample 2:', s)
  
# Example 3
s =now.strftime("%-I %p %S")
print('\nExample 3:', s)
  
# Example 4
s =now.strftime("%-j")
print('\nExample 4:', s)

Output:

 
Without formatting 2019-12-17 18:21:39.211378

Example 1: Tue-12-19

Example 2: Tuesday-12-2019

Example 3: 6 PM 39

Example 4: 351

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

The strftime() Method

The datetime object has a method for formatting date objects into readable strings.

The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:

Example

Display the name of the month:

 
import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))

Related Pages

For more, checkout Geeks For Geeks and W3Schools.