Python–cookbook–3.数字日期与时间

Python–cookbook–3.数字日期与时间

导入对应模块

from decimal import Decimal, localcontext
import math
import cmath  # 处理复数
from fractions import Fraction
import numpy as np
import random
import datetime
from dateutil.relativedelta import relativedelta
import calendar

数字的四舍五入

# 不要试着去舍入浮点值来”修正”表面上看起来正确的问题
print(round(1.23, 1))
print(round(1.25, 1))  # 内部机器二进制储存存在精度损失
print(round(-1.27, 1))

print(round(1627731, -1))  # 负数,舍入运算会作用在小数点前十位百位千位
print(round(1627731, -2))

执行精确的浮点数运算

a = 4.2
b = 2.1
print(a + b)
a1 = Decimal('4.2')
b1 = Decimal('2.1')
print(a1 + b1)
print(a1 + b1 == Decimal('6.3'))
a2 = Decimal('1.3')
b2 = Decimal('1.7')
print(a2 / b2)
with localcontext() as ctx:
    ctx.prec = 3  # 精度为3位小数
    print(a2 / b2)
nums = [1.23e+18, 1, -1.23e+18]
print(sum(nums))
print(math.fsum(nums))  # 更精确的计算

数字的格式化输出

# [<>^]?width[,]?(.digits)?
x = 1234.56789
print(format(x, '0.2f'))
print(format(x, '>10.1f'))  # 右对齐
print(format(x, '<10.1f'))
print(format(x, '^10.1f'))  # 居中
print(format(x, ','))  # 千位分隔符
print(format(x, '0,.1f'))  # 千位分隔符 + 保留一位小数
print(format(x, 'e'))
print(format(x, '0.2E'))  # 保留两位小数的大E指数计法
print('The value is {:0,.2f}'.format(x))

二八十六进制整数

x = 1234
print(bin(x))  # 0b
print(oct(x))  # 0o
print(hex(x))  # 0x
print(format(x, 'b'))  # 不输出前缀
print(format(x, 'o'))
print(format(x, 'x'))
# 对于负数,希望产生无符号数
x = -1
print(format(2**32 + x, 'b'))
print(format(2**32 + x, 'x'))
# 不同进制转换成整数
print(int('4d2', 16))
print(int('10011010010', 2))

字节到大整数的打包与解包

# 字节字符串解压成整数,大整数转换成字节字符串
data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
print(len(data))
print(int.from_bytes(data, 'little'))  # 转整数
print(int.from_bytes(data, 'big'))
x1 = 69120565665751139577663547927094891008
x2 = 94522842520747284487117727783387188
print(x1.to_bytes(16, 'little'))  # 转字节
print(x2.to_bytes(16, 'big'))

复数的数学运算

a = complex(2, 4)
b = 3 - 5j
print(a, a.real, a.imag, a.conjugate())  # 实部、虚部、共轭
print(a+b, a*b, a/b, abs(a))
print(cmath.sin(a), cmath.cos(a), cmath.exp(a))  # 正弦、余弦、平方根
print(cmath.sqrt(-1))

无穷大与NaN(非数字)

a = float('inf')
b = float('-inf')
c = float('nan')
print(a, b, c)
print(math.isinf(a), math.isinf(b), math.isnan(c))

分数运算

a = Fraction(5, 4)
b = Fraction(7, 16)
print(a+b, a*b)
c = a * b
print(c, c.numerator, c.denominator)  # 分子 分母
print(float(c))
print(c.limit_denominator(8))  # 限定分母大小
x = 3.75
y = Fraction(*x.as_integer_ratio())  # 转分数
print(y)

大型数组运算

# 使用numpy
ax = np.array([1, 2, 3, 4])
ay = np.array([5, 6, 7, 8])
print(ax * 2)
print(ax + 10)  # list会报错
print(ax + ay)
print(ax * ay)
def f(x):
    return 3*x**2 - 2*x + 7
print(f(ax))
print(np.sqrt(ax))
print(np.cos(ax))
grid = np.zeros(shape=(5, 5), dtype=float)  # 5*5二维
print(grid)
grid[1:3, 1:3] += 10
print(grid)

矩阵与线性代数运算

m = np.matrix([[1, -2, 3], [0, 4, 5], [7, 8, -9]])
print(m)
print(m.T)

随机选择

values = [1, 2, 3, 4, 5, 6]
print(random.choice(values))
print(random.sample(values, 3))  # 提取多个元素
random.shuffle(values)  # 打乱
print(values)
print(random.randint(0, 10))  # 生成随机整数
print(random.random())  # 生成0~1范围均匀分布的浮点数
print(random.getrandbits(16))  # 生成N位随机二进制整数
# 指定相同seed保证生成的随机数相同
# random.seed() # Seed based on system time or os.urandom()
# random.seed(12345) # Seed based on integer given
# random.seed(b'bytedata') # Seed based on byte data
# 除此外,random.uniform() 计算均匀分布随机数,random.gauss() 计算正态分布随机数

基本的日期与时间转换

# 表示一个时间段
a = datetime.timedelta(days=2, hours=6)
b = datetime.timedelta(hours=2.5)
c = a + b
print(c, type(c))
print(c.days, c.seconds/3600, c.total_seconds()/3600)
# 表示指定的日期和时间
a1 = datetime.datetime(2022, 4, 24, 1, 1, 1)  # year, month=None, day=None, hour=0, minute=0, second=0
print(a1, type(a1))
print(a1 + datetime.timedelta(days=2, hours=6))
now = datetime.datetime.now()
today = datetime.datetime.today()
print(now, type(now))
print(today, type(today))
# 使用 dateutil 处理时区,模糊时间范围,节假日计算
a2 = datetime.datetime(2022, 4, 24)
print(a2 + relativedelta(months=+1))
b2 = datetime.datetime(2022, 4, 23)
print(a2 - b2)
print(relativedelta(a2, b2))

计算最后一个周五的日期

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
            'Friday', 'Saturday', 'Sunday']
def get_previous_byday(dayname, start_date=None):
    if start_date is None:
        start_date = datetime.datetime.today()
    day_num = start_date.weekday()  # 6 : 'Sunday'
    day_num_target = weekdays.index(dayname)  # 4 : Friday
    days_ago = (7 + day_num - day_num_target) % 7
    if days_ago == 0:
        days_ago = 7
    target_date = start_date - datetime.timedelta(days=days_ago)
    return target_date
print(get_previous_byday('Friday'))  # 本周周五
print(now + relativedelta(weekday=4))  # 下一个周五

计算当权月份的日期范围

def get_month_range(start_date=None):
    if start_date is None:
        start_date = datetime.date.today().replace(day=1)  # 第一天
        _, days_in_month = calendar.monthrange(start_date.year, start_date.month)  # 该月总天数
        end_date = start_date + datetime.timedelta(days=days_in_month)
        return (start_date, end_date)
first_day, last_day = get_month_range()
print(first_day)
print(last_day)

字符串转换为日期

text = '2012-09-20'
y = datetime.datetime.strptime(text, '%Y-%m-%d')  # strptime性能很差
print(y)
z = datetime.datetime(2012, 9, 23, 21, 37, 4, 177393)
nice_z = datetime.datetime.strftime(z, '%A %B %d, %Y')
print(nice_z)

取当前时间的年月日

print(datetime.datetime.now())
# 取年
print(datetime.datetime.now().year)
# 取月
print(datetime.datetime.now().month)
# 取日
print(datetime.datetime.now().day)
# 取时
print(datetime.datetime.now().hour)
# 取分
print(datetime.datetime.now().minute)
# 取秒
print(datetime.datetime.now().second)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柴寺仓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值