Python语言之数字格式化与时间

(一)数值格式化

a = 120
f'{a}'
'120'
'数值:{:f}'.format(a)
'数值:120.000000'
f'数值:{a}'
'数值:120'
f'数值:{a:f}'
'数值:120.000000'
----------------------------------------
'{:,f}'.format(b)
'123,434,555.000000'
'{:,.2f}'.format(b)
'123,434,555.00'
------------------------------------------
x = 18
y  = 23
'{:.2f}'.format(x / y)
'0.78'
'{:.2%}'.format(x / y)
'78.26%'
--------------------------------------------

(二)随机数

>>> l = list(range(1,11))
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> import random
>>> random.choice(l)
7
>>> random.sample(l,3)
[8, 1, 6]
>>> random.shuffle(l)
>>> l
[4, 5, 10, 8, 6, 2, 7, 9, 1, 3]
----------------------------------------------
>>> random.randint(1,10)
2
#0-1的随机浮点数
>>> random.random()
0.29776082591472086
#给定数量bit位的随机数
>>> random.getrandbits(5)
12
>>> 

(三)日期

date(只考虑日期):

>>> datetime.MAXYEAR
9999
>>> datetime.date.today()
datetime.date(2020, 1, 6)
>>> today = datetime.date.today()
>>> today
datetime.date(2020, 1, 6)
>>> today.year
2020
>>> today.month
1
>>> today.weekday
<built-in method weekday of datetime.date object at 0x000002715A443690>
>>> today.weekday()
0
>>> today.isoweekday()
1
>>> birthday = datetime.date(1999,12,12)
>>> birthday
datetime.date(1999, 12, 12)
>>> 

time(只考虑时间):

>>> t = datetime.time(15,46,33)
>>> t.hour
15
>>> t.minute
46
>>> t.second
33

datetime(考虑时间和日期):

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2020, 1, 6, 21, 4, 38, 227222)
>>> now.day
6
>>> t = datetime.datetime.strptime(s,'%Y-%m-%d')
>>> t
datetime.datetime(2019, 12, 12, 0, 0)
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2020, 1, 6, 21, 7, 46, 481926)
>>> now.strftime('%Y/%m/%d')
'2020/01/06'
>>> d = datetime.datetime(2019,12,12,12,12)
>>> d
datetime.datetime(2019, 12, 12, 12, 12)
>>>  birthday = datetime.datetime(2019,11,11,11,11)
>>> birthday
datetime.datetime(2019, 11, 11, 11, 11)
>>> d - birthday
datetime.timedelta(31, 3660)
>>> diff = d - birthday
>>> diff.days
31
>>> diff.seconds
3660
>>> diff.total_seconds()
2682060.0
>>> o = datetime.datetime(2008,8,8,20,8)
>>> datetime.timedelta(days=100)
datetime.timedelta(100)
>>> o + datetime.timedelta(days=100)
datetime.datetime(2008, 11, 16, 20, 8)
>>> o + datetime.timedelta(days=-100)
datetime.datetime(2008, 4, 30, 20, 8)
>>> o + datetime.timedelta(seconds=3000)
datetime.datetime(2008, 8, 8, 20, 58)
posted @ 2020-01-06 21:20  sowhat1943  阅读(400)  评论(0编辑  收藏  举报