数值、日期与时间的操作

数值基本表达与设置:

a = 520
b = 12345.2662
c = -16462.2521
print('数值:{}'.format(a))  # 数值:520
print('数值:{}'.format(b))  # 数值:12345.2662

## 等同于如下:
print(f'数值:{a}')  # 数值:520
print(f'数值:{b}')  # 数值:12345.2662

print('数值:{:,}'.format(b))  # 数值:12,345.2662
print(f'数值:{b:,}')  # 数值:12,345.2662

print('数值:{:f}'.format(a))  # 数值:520.000000
print(f'数值:{a:f}')  # 数值:520.000000

print('数值:{:,.2f}'.format(b))  # 数值:12,345.27
print(f'数值:{b:,.2f}')  # 数值:12,345.27

数值随机数的产生:

lst = list(range(1, 11))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random

random.choice(lst)  # 随机从序列中拿出一个对象5
random.sample(lst, 3)  # 随机从序列中拿出3个对象[1 2 6]
random.shuffle(lst)  # 将lst随机打乱

random.randint() # 生成范围内的随机整数
random.random() # 生成随机浮点数

日期与时间的操作:

import datetime

today = datetime.date.today()  # 类方法,获取今天的时间
# print(today)  # 2020-02-08
# print(today.year)  # 2020
# print(today.day)  # 8号
# print(today.weekday())  # 星期五+1=六

birthdate = datetime.date(2018, 3, 12)  # 类实例方法,定义一个生日
# print(birthdate.year)
# print(birthdate.day)


now = datetime.datetime.now()  # 获取当前时间
# print(now)  # 2020-02-08 19:10:25.711994


s = '2018-3-15'
t = datetime.datetime.strptime(s, '%Y-%m-%d')  # 将字符串变为时间
# print(t)  # 2018-03-15 00:00:00

txt = now.strftime('%Y/%m/%d')  # 将时间变为字符串
# print(txt)  # 2020/02/08


# 定义时间加减
diff = now - t
print(diff)  # 695 days, 21:51:47.862336

o = datetime.datetime(2010, 8, 8, 20, 8)
ans = o + datetime.timedelta(days=100)
print(ans)  # 2010-11-16 20:08:00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值