PythonCookBook笔记——数字日期和时间

数字日期和时间

数字的四舍五入

round函数,指定值和小数位数。

>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254

精确的浮点数运算

>>> a = 4.2
>>> b = 2.1
>>> a + b
6.300000000000001
>>> (a + b) == 6.3
False

>>> from decimal import Decimal
>>> a = Decimal('4.2')
>>> b = Decimal('2.1')
>>> a + b
Decimal('6.3')
>>> print(a + b)
6.3
>>> (a + b) == Decimal('6.3')
True

数字的格式化输出

>>> x = 1234.56789
>>> # Two decimal places of accuracy
>>> format(x, '0.2f')
'1234.57'
>>> # Right justified in 10 chars, one-digit accuracy
>>> format(x, '>10.1f')
' 1234.6'
>>> # Left justified
>>> format(x, '<10.1f')
'1234.6 '
>>> # Centered
>>> format(x, '^10.1f')
' 1234.6 '
>>> # Inclusion of thousands separator
>>> format(x, ',')
'1,234.56789'
>>> format(x, '0,.1f')
'1,234.6'

二八十六进制整数

有时需要将整数转为二进制、八进制、十六进制的文本串。

>>> x = 1234
>>> bin(x)
'0b10011010010'
>>> oct(x)
'0o2322'
>>> hex(x)
'0x4d2'
>>> format(x, 'b')
'10011010010'
>>> format(x, 'o')
'2322'
>>> format(x, 'x')
'4d2'

>>> int('4d2', 16)
1234
>>> int('10011010010', 2)
1234

分数运算

>>> from fractions import Fraction
>>> a = Fraction(5, 4)
>>> b = Fraction(7, 16)
>>> print(a + b)
27/16
>>> print(a * b)
35/64
>>> # Getting numerator/denominator
>>> c = a * b
>>> c.numerator
35
>>> c.denominator
64
>>> # Converting to a float
>>> float(c)
0.546875
>>> # Limiting the denominator of a value
>>> print(c.limit_denominator(8))
4/7
>>> # Converting a float to a fraction
>>> x = 3.75
>>> y = Fraction(*x.as_integer_ratio())
>>> y
Fraction(15, 4)

随机选择

利用内置的random模块可以生成随机数或做随机选择。

random.choice(seq)可以从序列中随机抽取一个元素。

random.sample(seq, num)可以从指定序列中抽取指定个数的元素。

random.shuffle(seq)用于将有序序列打乱。

random.randint(start, end)用于从指定范围内生成随机整数。

random.random()不需参数,生成0-1之间的随机浮点数。

要注意的是,random模块使用Mersenne Twister算法来计算生成随机数,这是确定性算法,但可以通过random.seed()来修改初始化种子(默认以系统时间或系统提供的随机数)。

并且,random的函数不应该用于密码学应用,如加密。

基本的日期与时间转换

使用datetime模块。

timedelta()用于生成时间段(表示几年、几天、几小时),并且支持算术运算。

datetime()生成指定日期,也支持算术运算,可与timedelta()的值进行运算,并且该函数会自动考虑润年。

字符串转换为日期

有时需要将字符串格式日期转换为datetime对象以便进行运算,同样使用datetime模块。

strptime()接收字符串和一个匹配规则,返回一个datetime对象。

>>> from datetime import datetime
>>> text = '2012-09-20'
>>> y = datetime.strptime(text, '%Y-%m-%d')
>>> z = datetime.now()
>>> diff = z - y
>>> diff
datetime.timedelta(3, 77824, 177393)
>>>

必须注意的是,该方法性能极差,如果涉及到大量已知格式的日期转换,最好自己解析出对应日期并手动构建datetime对象。

转载于:https://www.cnblogs.com/ikct2017/p/9552810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值