Python strftime

Python strftime is a shorter version of string format time that allows formatting dates and times as per the requirement. As the name suggests, you can convert a given Python datetime object into a string representation using a specified strftime format option. For instance, you can use strftime to convert and display the date and time in “YYYY-MM-DD” or “H:M:S”.

The Python strftime function is a part of the datetime, time, and pandas module, and you must import these libraries. This article shows how to use strftime to parse datetime objects, a table of available formatting codes, and an example of each format option.

Python strftime function

It is used to format date and time and returns a string representation. The Python strftime function accepts the input as a datetime object and uses the directives to format them, and returns the output as a string.

The syntax of the Python strftime function in the datetime module is

datetime_Object_Value.strftime(Directives)

The List of available Python strftime directives and their descriptions.

DirectivesDescriptionOutput
%aShort Version of WeekdayWed
%AFull Version of WeekdayWednesday
%bShort Version of Month NameJan
%BFull Version of Month NameJanuary
%cLocal Version of Dt and tmThu May 23 10:35:32 2019
%dDay Number of a Month 01 to 3123
%fMicroseconds 000000 to 999999965060
%HHours 00 to 2315
%IHours 00 to 1210
%jDay Number of the Year 001 to 366320
%mMonth as a Number 01 to 1205
%MMinutes from 00 to 5935
%pAM or PMAM
%SSeconds from 00 to 5932
%UWeek Number of the Year from 00 to 53, where First Day of the Week = Sunday 20
%wWeekday as a Number from 0 to 6, Where 0 = Sunday4
%WWeek Number of the Year from 00 to 53, where First Day of the Week = Monday20
%xLocal Version of Date05/23/19
%XLocal of Time10:35:32
%yShort Version of Year19
%YFull Version of the Year2019
%zUTC Offset
%ZTimezone
%%A % character%

Python strftime in datetime module

The datetime module provides various functions to work with dates and times; strftime is one of them. To work with this strftime function, you must first import the datetime module.

import datetime

Next, you need a datetime object because this function accepts it as an input. So, use the datetime class to create an object. Again, this class has many methods to get the particular date & time parts, and we covered them in a different article.

dt = datetime.datetime.now()

Once you have a datetime object inside the strftime function, use any of the directives mentioned above to display the date and times in the desired format. The following examples list gives an idea of most of the used codes.

Python datetime strftime Example

This Python strftime example uses the datetime class now() function to get the current data. Next, we used the strftime function to return the Year, Month name, Month Number, Day Number, etc., from today’s date and time.

Get the Year, Month name, Month Number, and Day Number from Today’s date using this function.

from datetime import datetime

dt = datetime.now()

print('Current Date = ', dt)

print('Year in Short            = ', dt.strftime('%y'))
print('Current Year             = ', dt.strftime('%Y'))
print('Month Name in Short      = ', dt.strftime('%b'))
print('Month Name               = ', dt.strftime('%B'))
print('Month Number             = ', dt.strftime('%m'))
print('Day Number of the Month  = ', dt.strftime('%d'))
print('Day Number of the Year   = ', dt.strftime('%j'))
print('Week No of Year 00 to 53 = ', dt.strftime('%U'))
print('Week Number of Year      = ', dt.strftime('%W'))
print('Short Version of Weekday = ', dt.strftime('%a'))
print('Full Version of Weekday  = ', dt.strftime('%A'))
print('Weekday as a Number      = ', dt.strftime('%w'))
Current Date =  2023-05-12 15:27:30.520082
Year in Short            =  23
Current Year             =  2023
Month Name in Short      =  May
Month Name               =  May
Month Number             =  05
Day Number of the Month  =  12
Day Number of the Year   =  132
Week No of Year 00 to 53 =  19
Week Number of Year      =  19
Short Version of Weekday =  Fri
Full Version of Weekday  =  Friday
Weekday as a Number      =  5

Creating string from a timestamp

from datetime import datetime

timestamp = 1487958621
dt = datetime.fromtimestamp(timestamp)

print("datetime object =", dt)

a = dt.strftime("%d/%m/%Y, %H:%M:%S")
print("Example 1 =", a)

b = dt.strftime("%A %d %b, %Y")
print("Example 2 =", b)

c = dt.strftime("%d %B, %Y")
print("Example 3 =", c)

d = dt.strftime("%I %p")
print("Example 4 =", d)
datetime object = 2017-02-24 23:20:21
Example 1 = 24/02/2017, 23:20:21
Example 2 = Friday 24 Feb, 2017
Example 3 = 24 February, 2017
Example 4 = 11 PM

Use Locales to format datetime

We use the Python strftime function to return the local version of Date, Time, and DateTime of the current date and time.

from datetime import datetime
 
dt = datetime.now()
 
print(dt)
 
print('Local Version = ', dt.strftime('%c'))
print('Local Version of Dt          = ', dt.strftime('%x'))
print('Local Version of Tm          = ', dt.strftime('%X'))
2021-05-02 16:00:01.379106
Local Version = Sun May 2 16:00:01 2021
Local Version of Dt = 05/02/21
Local Version of Tm = 16:00:01

Convert time to string format

Let me use this Python strftime to return the Hours, Minutes, Seconds, Microseconds, AM, or PM from the current DateTime class.

from datetime import datetime

dt = datetime.now()
 
print(dt)
print('Hours                 = ', dt.strftime('%H'))
print('Hours                 = ', dt.strftime('%I'))
print('Minutes               = ', dt.strftime('%M'))
print('Seconds               = ', dt.strftime('%S'))
print('Microseconds          = ', dt.strftime('%f'))
print('AM or PM              = ', dt.strftime('%p'))
print('% Charcter           = ', dt.strftime('%%'))

Print Hours, Minutes, Seconds, and Microseconds using this method output

2021-05-02 15:57:46.656409
Hours = 15
Hours = 03
Minutes = 57
Seconds = 46
Microseconds = 656409
AM or PM = PM
% Charcter = %

Python strftime to format DateTime object

So far, we are using one Python directive to return one part of the Date. However, it is very useful to format the date and time in the required format. It displays the current date and time in Year/month/day Hour:Minute: Second AM/PM.

import datetime
 
dt = datetime.datetime.now()
 
print(dt)
 
print(dt.strftime('%Y/%m/%d %H:%M:%S %p'))
2021-05-02 15:54:05.603666
2021/05/02 15:54:05 PM

Few more formatting options.

Python strftime 7

Python strftime in time module Example

In Python programming, apart from the datetime module, the time module also has the strftime function. To work with this, you have to import the time library.

The syntax of the Python strftime function in the time module is shown below.

time.strftime(Directives, time_object_value)

time Example

Here, we used the localtime function in the time library and applied a few of the available Python strftime format codes.

import time
 
dt = time.localtime(1234567)
 
print(time.strftime('%Y/%M/%d %H:%M:%S %p', dt))
print(time.strftime('%m/%d/%y %H:%M:%S', dt))
print(time.strftime('%d-%m-%Y %I:%M:%S %p', dt))
 
print(time.strftime('%I:%M:%S %p', dt))
1970/26/15 12:26:07 PM
01/15/70 12:26:07
15-01-1970 12:26:07 PM
12:26:07 PM

Python strftime function in pandas module

The strftime function available in the pandas module is the most powerful one. Instead of applying on datetime object, pandas allows you to apply strftime on DataFrame and Series. So, you can use this function to format dates and times in a complete table.

Series Example

In this example, we declared a series of dates and used the strftime function with %A %d %B %Y %H:%M:%S %p format to display the Weekday name, day number, month name, Year, Hours, Minutes, Seconds, and AM or PM.

import pandas as pd

data = pd.Series(['2015-04-06', '2016-05-10', '2017-06-15', '2018-07-25'])

dts = pd.to_datetime(data)

formatted = dts.dt.strftime('%A %d %B %Y %H:%M:%S %p')

print(formatted)
0      Monday 06 April 2015 00:00:00 AM
1       Tuesday 10 May 2016 00:00:00 AM
2     Thursday 15 June 2017 00:00:00 AM
3    Wednesday 25 July 2018 00:00:00 AM
dtype: object

DataFrame Example

This simple example shows how to use this function to convert date and time columns in a table to string representation of a given format.

import pandas as pd

data = {'name': ['John', 'Mike', 'Suresh', 'Tracy'],
         'Age': [25, 32, 30, 26],
         'Profession': ['Developer', 'Analyst', 'Admin', 'HR'],
         'Salary':[10000, 12000, 9000, 11000],
         'date': ['2015-04-06', '2016-05-09', '2017-06-11', '2018-07-25']
         }

df = pd.DataFrame(data)

df['date'] = pd.to_datetime(df['date'])
df['formatted'] = df['date'].dt.strftime('%A, %d %B %Y')

print(df)
     name  Age Profession  Salary       date                formatted
0    John   25  Developer   10000 2015-04-06    Monday, 06 April 2015
1    Mike   32    Analyst   12000 2016-05-09      Monday, 09 May 2016
2  Suresh   30      Admin    9000 2017-06-11     Sunday, 11 June 2017
3   Tracy   26         HR   11000 2018-07-25  Wednesday, 25 July 2018