Post

Date and string format in python

Date and string format in python

在 Python 中生成字符串有 3 种方式,现在比较建议的是使用 f-str 的方式,官方说性能更加好。本文主要 介绍在格式化时有哪些格式可以选择。

String

%

1
2
3
4
5
a = 42
b = "%d" % a

c = "answer to everything"
d = "%s %s" % (b, c)

format

1
2
3
4
5
6
7
8
9
10
11
12
13
a = "{} {}"
b = 1
c = 2
d = a.format(b, c)

a = "{bb} {cc}"
d = a.format(bb=b, cc=c)

person = {"first": "zhang", "last": "san"}
d = "{p[first]}-{p[last]}".format(p=person)

a = "{1} {0}"
d = a.format(b, c)  # 交换位置

f-str

基本上所有的 format 支持得做法 f-str 都是支持的。这里展开介绍下具体的格式。

进制转化

1
2
3
4
5
6
7
8
9
10
a = 13
print(f"{a:o}")
print(f"{a:b}")
print(f"{a:x}")
print(f"{a:d}")

b = 88.3998128733

print(f"{b:.4f}")
print(f"{b:.4e}")  # 科学技术法

对齐

1
2
3
4
5
6
7
8
a = 13

print(f"{a:04}")   # 默认填充左边

# 自定义填充字符
print(f"{a:_>04}") # 填充左边
print(f"{a:_<04}") # 填充右边
print(f"{a:_^04}") # 填充左右

benchmark

1
2
3
4
5
python -m timeit "a=1;b=f'{a}'"
# 2000000 loops, best of 5: 102 nsec per loop

python -m timeit "a=1;b='{a}'.format(a=a)"
# 1000000 loops, best of 5: 336 nsec per loop

可以看出 f-strformat 的性能还是高不少。

time format

1
2
3
4
5
6
7
from datetime import datetime as dt

now = dt.now()

format = "%Y-%m-%d %H:%M:%S %a"

print(now.strftime(format))
CodeExampleDescription 
%aSunWeekday as locale’s abbreviated name. 
%ASundayWeekday as locale’s full name. 
%w0Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 
%d08Day of the month as a zero-padded decimal number. 
%-8Day of the month as a decimal number. (Platform specific) 
%bSepMonth as locale’s abbreviated name. 
%BSeptemberMonth as locale’s full name. 
%m09Month as a zero-padded decimal number. 
%-9Month as a decimal number. (Platform specific) 
%y13Year without century as a zero-padded decimal number. 
%Y2013Year with century as a decimal number. 
%H07Hour (24-hour clock) as a zero-padded decimal number. 
%-H7Hour (24-hour clock) as a decimal number. (Platform specific) 
%I07Hour (12-hour clock) as a zero-padded decimal number. 
%- 7Hour (12-hour clock) as a decimal number. (Platform specific)
%pAMLocale’s equivalent of either AM or PM. 
%M06Minute as a zero-padded decimal number. 
%-M6Minute as a decimal number. (Platform specific) 
%S05Second as a zero-padded decimal number. 
%-S5Second as a decimal number. (Platform specific) 
%f000000Microsecond as a decimal number, zero-padded on the left. 
%z+0000UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive). 
%ZUTCTime zone name (empty string if the object is naive). 
%j251Day of the year as a zero-padded decimal number. 
%-j251Day of the year as a decimal number. (Platform specific) 
%U36Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 
%W35Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 
%cSun Sep 8 07:06:05 2013 Locale’s appropriate date and time representation.  
%x09/08/13Locale’s appropriate date representation. 
%X07:06:05Locale’s appropriate time representation. 
%%%A literal ‘%’ character. 

Reference

This post is licensed under CC BY 4.0 by the author.