数值
格式化
>>>a = 520
>>>b = 12345678.12345678
>>>c = -123456.654321
>>>type(a)
<class 'int'>
>>>type(b)
<class 'float'>
>>>type(c)
<class 'float'>
>>>f'数值:{a}'
'数值:520'
>>>f'数值:{b}'
'数值:12345678.12345678'
>>>'数值:{}'.format(a)
'数值:520'
>>>'数值:{:f}'.format(a)
'数值:520.000000'
小数位处理
>>>import math
>>>math.trunc(b)
12345678
>>>math.trunc(123.987)
123
>>>math.floor(b)
12345678
>>>math.floor(123.987)
123
>>>math.ceil(b)
12345679
>>>round(b,3)
12345678.123
随机数
random.choice()序列特定一个值
random.sample()获取特定数量值
random.shuffle()打乱顺序
random.randint()生成范围内的随机整数
random.random()小于1浮点型
random.getrandbits()指定bit位数的随机数
>>>import random
>>>random.choice(lis)
7
>>>random.choice(lis)
3
>>>random.choice(lis)
2
>>>random.sample(lis,3)
[1, 9, 2]
>>>random.sample(lis,3)
[2, 10, 5]
random.shuffle(lis)
>>>lis
[10, 9, 2, 7, 5, 3, 1, 6, 8, 4]
>>>random.randint(1,10)
1
>>>random.randint(1,10)
10
>>>random.randint(1,10)
1
>>>random.random()
0.6901719401802565
>>>random.random()
0.11285629061717328
>>>random.random()
0.7941549088345529
>>>random.getrandbits(10)
582
>>>random.random()
0.5092749755314189
日期时间
年月日date
时分秒time
一起datetime:year month day
datetime基础
>>>import datetime
>>>datetime.MAXYEAR
9999
>>>datetime.MINYEAR
1
>>>today = datetime.date.today()
today
>>>datetime.date(2019, 11, 16)
>>>today.year
2019
>>>today.month
11
>>>today.day
16
>>>today.weekday()
5
>>>today.isoweekday()
6
>>>birthdate = datetime.date(2019,11,18)
>>>t = datetime.time(13,14,00)
>>>now = datetime.datetime.now()
now
>>>datetime.datetime(2019, 11, 16, 22, 8, 47, 373777)
>>>now.year
2019
>>>now.day
16
>>>now.microsecond
373777
注意:
weekday:从0开始
isoweekday:国际标准,星期几
格式转换
- 字符串到日期时间 datetime.datetime.strptime(‘txt’,‘格式’)
- 日期时间到字符串 datetime.datetime.strftime(‘格式’)
- 占位符
%Y 四位年份
%y 二位年份
%m 二位月份
%d 二位日期
%H 二位分钟
%S 二位秒数
%f 微秒
%w 星期数,0-6
>>>s = '2019-11-11'
>>>type(s)
<class 'str'>
>>>t = datetime.datetime.strptime(s,'%Y-%m-%d')
>>>t
datetime.datetime(2019, 11, 11, 0, 0)
>>>now = datetime.datetime.now()
>>>now
datetime.datetime(2019, 11, 16, 22, 15, 44, 885542)
>>>txt = now.strftime('%Y/%m/%d')
>>>txt
'2019/11/16'
时间差timedelta
days
seconds
hours
import datetime
d = datetime.datetime(2019,11,11,11,11)
birthday = datetime.datetime(1996,8,26,10,10)
d-birthday
datetime.timedelta(days=8477, seconds=3660)
diff = d - birthday
diff.days
8477
diff.seconds
3660
diff.total_seconds()
732416460.0
O = datetime.datetime(2008,8,8,20,8)
O + datetime.timedelta(days = 100)
datetime.datetime(2008, 11, 16, 20, 8)
result = d + datetime.timedelta(days = -100)
result
datetime.datetime(2019, 8, 3, 11, 11)
result.hour
11
一次性导入
from datetime import date,time,datetime,timedelta