Python 輸出百分比的兩種方式
方式1:直接使用參數格式化:{:.2%}
{:.2%}: 顯示小數點后2位
顯示小數點后2位: >>> print('percent: {:.2%}'.format(42/50)) percent: 84.00%
不顯示小數位:{:.0%},即,將2改為0:
>>> print('percent: {:.0%}'.format(42/50)) percent: 84%
方式2:格式化為float,然后處理成%格式: {:.2f}%
與方式1的區別是:
(1) 需要對42/50乘以 100 。
(2) 方式2的%在{ }外邊,方式1的%在{ }里邊。
顯示小數點后2位:
>>> print('percent: {:.2f}%'.format(42/50*100)) percent: 84.00%
顯示小數點后1位:
>>> print('percent: {:.1f}%'.format(42/50*100)) percent: 84.0%
只顯示整數位:
>>> print('percent: {:.0f}%'.format(42/50*100)) percent: 84%
說明
{ } 的意思是對應format()的一個參數,按默認順序對應,參數序號從0開始,{0}對應format()的第一個參數,{1}對應第二個參數。例如:
默認順序:
>>> print('percent1: {:.2%}, percent2: {:.1%}'.format(42/50, 42/100)) percent1: 84.00%, percent2: 42.0%
指定順序:
{1:.1%}對應第2個參數; {0:.1%}對應第1個參數。
>>> print('percent2: {1:.1%}, percent1: {0:.1%}'.format(42/50, 42/100)) percent2: 42.0%, percent1: 84.0%
取小數點后幾位 (2可以隨意改變 換成3就是保留三位小數)
>>> a = 1 >>> b = 3 >>> print(a/b) >>> #方法一: ... print(round(a/b,2)) int類型 0.0 >>> #方法二: ... print(format(float(a)/float(b),'.2f')) str類型 0.33 >>> #方法三: ... print ('%.2f' %(a/b)) str類型 0.00
時間格式轉換
data['rewardtime'] = datetime.datetime.strftime(data['rewardtime'], "%Y-%m-%d %H:%M:%S") %Y-%m-%d %H:%M:%S 年月日 時分秒 按自己需要的就好 data['rewardtime']自己的時間