数值基本表达与设置:
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