Python strftime Function | milliseconds | Examples

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

Syntax

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

# YYYY-MM-DD HH:MM:SS.MS 
xt = datetime.datetime(2018, 10, 10, 3, 38, 1, 844628)
print(xt)

print(xt.strftime("%a"))

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)))
print(xt)

print(xt.strftime("%a"))

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

Directive Description Example
%a Short name of a weekday Fri
%A Full name of Weekday Friday
%w Weekday as a number 0-6, 0 is Sunday – 0 Monday – 1 … 5
%d Day of month 01-31 01
%b Month name, short version Oct
%B Month name, full version October
%m Month as a number 01-12 10
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 00
%I Hour 00-12 12
%p AM/PM AM
%M Minute 00-59 38
%S Second 00-59 01
%f Microsecond 000000-999999 844628
%z UTC offset +0100
%Z Timezone UTC+01:00
%j Day number of year 001-366 283
%U Week number of year, Sunday as the first day of the week, 00-53 40
%W Week number of year, Monday as the first day of the week, 00-53 41
%c Local version of date and time Wed Oct 10 03:38:01 2018
%x Local version of date 10/10/18
%X Local version of time 03: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

This site uses Akismet to reduce spam. Learn how your comment data is processed.