python基础(十):数值与日期

数值

格式化

>>>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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值