The Wayback Machine - https://web.archive.org/web/20240914052842/https://www.geeksforgeeks.org/python-strftime-function//
Open In App

Python strftime() function

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Python Strftime() Syntax

Syntax: datetime_obj.strftime(format)

Parameters: 

  • Format: consists of various format codes that define specific parts of the date and time.

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

Strftime() Method in Python Example

The Python datetime library includes a method called strftime(). You can utilize a variety of the format codes it offers to build the necessary string representation. Let’s explore the Python date time string strftime() function’s example:

Python
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)

Output

2023-07-18 06:24:12

Time complexity: O(1)
Auxiliary Space: O(1)

Using Strftime() from Datetime Module

In this code, we are using the strftime() method from the datetime module to convert python date time string.

Python
# Python program to demonstrate
# strftime() function

from datetime import datetime 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

Time complexity: O(1)
Auxiliary Space: O(1)

Formatting Date and Time with AM/PM

In this code, we are using the strftime() method from the datetime module to format the date and time with AM/PM format to Python date time string.

Python
from datetime import datetime as dt

date = dt.now()
formatted_date = date.strftime("%B %d, %Y")
print(formatted_date)

time = dt.now()
formatted_time = time.strftime("%I:%M:%S %p")
print(formatted_time)

Output

July 18, 2023
06:52:17 AM

Time complexity: O(1)
Auxiliary Space: O(1)

Combining Different Format Codes

In this code, we are using the strftime() method from the datetime module combining different format codes for a specific format and also custom string with multiple format codes to Python date time string.

Python
from datetime import datetime as dt

custom = dt.now()
formatted_custom = custom.strftime("Today is %A, %B %d, %Y")
print(formatted_custom)

combined = dt.now()
formatted_combined = combined.strftime("%d/%m/%Y %H:%M:%S")
print(formatted_combined)

Output

Today is Tuesday, July 18, 2023
18/07/2023 06:50:49

Time complexity: O(1)
Auxiliary Space: O(1)

List of Format Codes

Reference table for the format codes.

DirectiveMeaningOutput Format
%aAbbreviated weekday name.Sun, Mon,….
%AFull weekday name.Sunday, Monday,…..
%wWeekday as a decimal number.0, 1,….., 6
%dDay of the month as a zero added decimal.01, 02,…., 31
%-dDay of the month as a decimal number.1, 2,…., 30
%bAbbreviated month name.Jan, Feb,…., Dec
%BFull month name.January, February,….
%mMonth as a zero added decimal number.01, 02,…., 12
%-mMonth as a decimal number.1, 2,….., 12
%yYear without century as a zero added decimal number.00, 01,…, 99
%-yYear without century as a decimal number.0, 1,…, 99
%YYear with century as a decimal number.2013, 2019 etc.
%HHour (24-hour clock) as a zero added decimal number.00, 01,….., 23
%-HHour (24-hour clock) as a decimal number.0, 1,…., 23
%IHour (12-hour clock) as a zero added decimal number.01, 02,…, 12
%-IHour (12-hour clock) as a decimal number.1, 2,…,12
%pLocale’s AM or PM.AM, PM
%MMinute as a zero added decimal number.00, 01,…., 59
%-MMinute as a decimal number.0, 1,…, 59
%SSecond as a zero added decimal number.00, 01,…, 59
%-SSecond as a decimal number.0, 1,…., 59
%fMicrosecond as a decimal number, zero added on the left.000000 – 999999
%zUTC offset in the form +HHMM or -HHMM. 
%ZTime zone name. 
%jDay of the year as a zero added decimal number.001, 002,….., 366
%-jDay of the year as a decimal number.1, 2,…., 366
%UWeek number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0.00, 01,…., 53
%WWeek number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.00, 01,….., 53

Python strftime() function – FAQs


What is strftime() in Python?

strftime() is a method in Python that formats date and time objects into readable strings based on specified format codes. It is part of the datetime module.

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: '2023-12-25 15:30:00'

What is strptime() function in Python?

strptime() is a function in Python that parses a string representing a date and time and returns a datetime object. It requires a corresponding format string to interpret the input string.

from datetime import datetime

date_str = "2023-12-25 15:30:00"
date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(date_obj) # Output: 2023-12-25 15:30:00

How to use strftime in DataFrame?

To use strftime in a Pandas DataFrame, you can apply it to datetime columns to convert them into formatted strings.

import pandas as pd

# Create a DataFrame with a datetime column
df = pd.DataFrame({'date': pd.to_datetime(['2023-01-01', '2023-12-25', '2023-07-04'])})

# Apply strftime to format the datetime column
df['formatted_date'] = df['date'].dt.strftime("%Y-%m-%d")
print(df)

What is the difference between strptime and strftime in Python?

strptime: Parses a string to create a datetime object.

strftime: Formats a datetime object to create a string.

from datetime import datetime

# strptime example
date_str = "2023-12-25 15:30:00"
date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

# strftime example
formatted_date = date_obj.strftime("%Y-%m-%d")
print(formatted_date) # Output: '2023-12-25'

What is dt.strftime in Python?

dt.strftime is a method used in Pandas to format datetime columns in a DataFrame. It is similar to strftime() in the datetime module but is used with Pandas datetime objects.

import pandas as pd

# Create a DataFrame with a datetime column
df = pd.DataFrame({'date': pd.to_datetime(['2023-01-01', '2023-12-25', '2023-07-04'])})

# Apply dt.strftime to format the datetime column
df['formatted_date'] = df['date'].dt.strftime("%Y-%m-%d")
print(df)

These methods are essential for handling and manipulating date and time data in Python and Pandas, providing flexibility for various formatting and parsing needs.



Similar Reads

time.strftime() function in Python
As time module provides various time-related functions. So it is necessary to import the time module otherwise it will through error because of the definition of time.strftime(format[, t]) is present in time module.time.strftime(format[, t]) function convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a stri
5 min read
Python | Pandas DatetimeIndex.strftime()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.strftime() function convert to Index using specified date_format. The function return an Index of formatted strings
2 min read
Python | Pandas Period.strftime
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Period.strftime() function returns the string representation of the Period, depending on the selected format. format must be a st
2 min read
Python | Pandas PeriodIndex.strftime
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas PeriodIndex.strftime() function return an array of formatted strings specified by date_format, which supports the same string for
2 min read
How to Format date using strftime() in Python ?
In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime(). Syntax: time.strftime(format[, sec]) sec: This is the time in number of seconds to be formatted. f
2 min read
Pandas Series dt.strftime() Method | Change Date Format in Series
The dt.strftime() method converts the datetime objects in the Pandas Series to a specified date format. The function returns an index of formatted strings specified by date_format, which supports the same string format as the Python standard library. Example[GFGTABS] Python import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1
3 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a U
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Prefix sum array in Python using accumulate function
We are given an array, find prefix sums of given array. Examples: Input : arr = [1, 2, 3] Output : sum = [1, 3, 6] Input : arr = [4, 6, 12] Output : sum = [4, 10, 22] A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, ...} are a, a+b, a+b+c and so on. We can solve this problem
1 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni
3 min read
Python | Permutation of a given string using inbuilt function
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA We have existing solution for this problem please refer Permutations of a given
2 min read
Article Tags :
Practice Tags :