Skip to content

Python strftime Function | milliseconds | Examples

  • by

Python strftime function return string format of given date and time object according to the specified format. In Easy word strftime() is used to convert a time to string. To get strftime function use in the program you need to import the time or DateTime module in the program.

Python strftime Function | milliseconds | Examples

strftime = string format timestamp or strftime = string from time or strftime = string format time


time.strftime(format[, t])

Parameter values

  • format – strftime() function takes one parameter format to specify the format of the returned string.

Python strftime Example

This example using a time object to get string date format

import time

# YYYY-MM-DD HH:MM:SS:MS timezone
t = (2018, 10, 10, 8, 58, 17, 3, 44, 0)

t = time.mktime(t)
print(time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t)))

Output: Oct 10 2018 03:28:17

Another example using datetime 

import datetime

xt = datetime.datetime(2018, 10, 10, 3, 38, 1, 844628)


Output: 2018-10-10 03:38:01.844628

Format codes in strftime:

Here are format codes used in strftime.

import datetime

# YYYY-MM-DD HH:MM:SS.MS timezone
xt = datetime.datetime(2018, 10, 10, 3, 38, 1, 844628, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))


Output: 2018-10-10 03:38:01.844628+01:00

%aShort name of a weekdayFri
%AFull name of WeekdayFriday
%wWeekday as a number 0-6, 0 is Sunday – 0 Monday – 1 …5
%dDay of month 01-3101
%bMonth name, short versionOct
%BMonth name, full versionOctober
%mMonth as a number 01-1210
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2300
%IHour 00-1212
%MMinute 00-5938
%SSecond 00-5901
%fMicrosecond 000000-999999844628
%zUTC offset+0100
%jDay number of year 001-366283
%UWeek number of year, Sunday as the first day of the week, 00-5340
%WWeek number of year, Monday as the first day of the week, 00-5341
%cLocal version of date and timeWed Oct 10 03:38:01 2018
%xLocal version of date10/10/18
%XLocal version of time03:38:01
%%A % character%

Note: Examples are based on datetime.datetime(2018, 10, 10, 3, 38, 1, 844628)

QA: How to convert strftime or string format to timestamp/Date in python?

It can be an interview question for a company, as we show upper details and example we can convert strftime to date.

Do comment if you have any doubts and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *