Documentation

datetime.format

Return a str created using the passed format fmt.

Arguments:

def datetime.format(
  dt: <datetime> = None,
  fmt: <str> = None,
):

Returns <str>.

Example:

long_ago = datetime.from_unix(ts=100000000)

# date_string == "Saturday, March 3, 1973 9:46:40 AM"
date_string = datetime.format(dt=long_ago, fmt="dddd, MMMM D, YYYY h:mm:ss A")

Tokens

The following tokens are currently supported in the fmt string:

Token Output
Year YYYY 2000, 2001, 2002 ... 2012, 2013
YY 00, 01, 02 ... 12, 13
Y 2000, 2001, 2002 ... 2012, 2013
Quarter Q 1 2 3 4
Qo 1st 2nd 3rd 4th
Month MMMM January, February, March ...
MMM Jan, Feb, Mar ...
MM 01, 02, 03 ... 11, 12
M 1, 2, 3 ... 11, 12
Mo 1st 2nd ... 11th 12th
Day of Year DDDD 001, 002, 003 ... 364, 365
DDD 1, 2, 3 ... 4, 5
Day of Month DD 01, 02, 03 ... 30, 31
D 1, 2, 3 ... 30, 31
Do 1st, 2nd, 3rd ... 30th, 31st
Day of Week dddd Monday, Tuesday, Wednesday ...
ddd Mon, Tue, Wed ...
dd Mo, Tu, We ...
d 0, 1, 2 ... 6
Days of ISO Week E 1, 2, 3 ... 7
Hour HH 00, 01, 02 ... 23
H 0, 1, 2 ... 23
hh 01, 02, 03 ... 11, 12
h 1, 2, 3 ... 11, 12
Minute mm 00, 01, 02 ... 58, 59
m 0, 1, 2 ... 58, 59
Second ss 00, 01, 02 ... 58, 59
s 0, 1, 2 ... 58, 59
Fractional Second S 0 1 ... 8 9
SS 00, 01, 02 ... 98, 99
SSS 000 001 ... 998 999
SSSS ... 000[0..] 001[0..] ... 998[0..] 999[0..]
SSSSSS
AM / PM A AM, PM
Timezone Z -07:00, -06:00 ... +06:00, +07:00
ZZ -0700, -0600 ... +0600, +0700
z Asia/Baku, Europe/Warsaw, GMT ...
zz EST CST ... MST PST
Seconds timestamp X 1381685817, 1234567890.123
Milliseconds timestamp x 1234567890123

Localized Formats

Because preferred formatting differs based on locale, there are a few tokens that can be used to format an instance based on its locale.

Time LT 8:30 PM
Time with seconds LTS 8:30:25 PM
Month numeral, day of month, year L 09/04/1986
Month name, day of month, year LL September 4 1986
Month name, day of month, year, time LLL September 4 1986 8:30 PM
Month name, day of month, day of week, year, time LLLL Thursday, September 4 1986 8:30 PM

Escaping Characters

To escape characters in format strings, you can wrap the characters in square brackets.