python基础
字典dict
字典排序
name = ['达拉斯', '大幅', '热个', '个胡', '圣啊']
age = [31, 32, 33, 34, 35]
index = [5, 2, 3, 4, 1]
diclist = []
for i in range(len(name)):
dic = {'name': name[i], 'age': age[i], 'index': index[i]}
diclist.append(dic)
# 字典排序
c = sorted(diclist, key=lambda diclist: diclist['index'], reverse=False)
print(c)
列表list
列表生成
lis = [i for i in range(5)]
print(lis)
列表切片
a = ["one", "two", "3", 4, 5]
b = a[0:3] # 简单切片
print(b)
c = a[0:3:1] # 带步长
print(c)
d = a[::-1] # 相当于反转列表
print(d)
列表排序
a = ["第一","第二","第三","第四","第五","第六"]
# 获得列表排序序号
b = np.argsort(a)
c = a.sort()
d = a.sort(reverse=True) # sort 不产生新的list
newlist1 = sorted(a) # sorted产生一个新的list
newlist2 = sorted(a, reverse=True)
时间和日期time and date
导入库
import datetime
import time
import pyodbc
# 数据库中的日期可以直接加.strftime("%Y-%m-%d %X")转成字符串
时间戳
# 时间戳 1640136459.9968226
timestamp = time.time()
print('时间戳:', timestamp)
结构化时间
# 结构化时间time.struct_time(tm_year=2021, tm_mon=12, tm_mday=22, tm_hour=9, tm_min=27, tm_sec=39, tm_wday=2, tm_yday=356, tm_isdst=0)
st = time.localtime()
print(st)
"""
属性 值
tm_year(年) 比如2011
tm_mon(月) 1 - 12
tm_mday(日) 1 - 31
tm_hour(时) 0 - 23
tm_min(分) 0 - 59
tm_sec(秒) 0 - 61
tm_wday(weekday) 0 - 6(0表示周日)
tm_yday(一年中的第几天) 1 - 366
tm_isdst(是否是夏令时) 默认为-1
"""
结构时间转时间戳
# 结构时间转时间戳
ts_st = time.mktime(time.localtime())
print(ts_st)
时间戳转结构时间
# 时间戳转结构时间1640115563.0710912
print(time.localtime(1640115563.0710912))
# 间戳转日期
s = time.time()
print(s)
a = datetime.date.fromtimestamp(s)
print(a, type(a))
b = a.timetuple() # 返回日期对应的time.struct_time对象;通过这个把datetime.date转成time.struct_time
print(b)
c = time.mktime(b) # 然后又可以转回时间戳
print(c)
# 此时的c跟最初的s比,已经失去了时间信息
# 这时候可以把a的结构时间转成格式化时间
d = a.strftime("%Y%m%d") # 把datetime.date格式转化成需要的字符串格式
print(d)
# 时间戳转日期时间
# 根据时间戳创建datetime对象 2021-12-22 10:27:29.141444 <class 'datetime.datetime'>
a = datetime.datetime.fromtimestamp(time.time())
print(a, type(a))
格式化时间转结构时间
# 格式化时间转结构时间
a = time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')
print(a, type(a))
# time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16,
# tm_min=37, tm_sec=6, tm_wday=3, tm_yday=125, tm_isdst=-1) <class 'time.struct_time'>
b = datetime.datetime.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')
print(b, type(b))
# 2011-05-05 16:37:06 <class 'datetime.datetime'>
结构时间转格式化时间
# 结构时间转格式时间
a1 = time.strftime("%Y-%m-%d %X")
a2 = time.strftime("%x %X")
time.strftime("%Y-%m-%d %X", time.localtime())
print(a1) # 2021-12-22 09:54:52
print(a2) # 12/22/21 09:54:52
# 把datetime.datetime转成想要的字符串格式
a = datetime.datetime.now().strftime("%Y-%m-%d %X")
print(a, type(a))
其他时间样式
# 其他时间样式 Wed Dec 22 09:49:39 2021 <class 'str'>
d = time.asctime(time.localtime())
c = time.ctime(time.time())
print(d, type(d))
print(c, type(c))
# c 和 d 都是字符串
计时
# 计时和延迟,延时,delay,睡眠
start = time.time()
time.sleep(0.1)
elapsed = (time.time() - start)
print("用时:", elapsed)
日期
# 获取今天日期 2021-12-22 <class 'datetime.date'>
jtrq = datetime.date.today()
print(jtrq, type(jtrq))
# 2021-12-22 <class 'str'>
strjtrq = str(jtrq)
print(strjtrq, type(strjtrq))
日期时间
a = datetime.datetime.today()
print(a, type(a)) # 2021-12-22 10:28:48.867435 <class 'datetime.datetime'>
b = datetime.datetime.now()
print(b, type(b)) # 2021-12-22 10:28:48.867435 <class 'datetime.datetime'>
# a和b是一样的
# 获取数据库需要的日期时间datetime格式的日期date
today = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
日期偏移
# datetime的日期偏移
# timedelta类 日期加减 日期偏移
dt1 = datetime.datetime.now() + datetime.timedelta(days=-1) # 昨天
dt2 = datetime.datetime.now() - datetime.timedelta(days=1) # 昨天
dt3 = datetime.datetime.now() + datetime.timedelta(days=1) # 明天
print(dt1, dt2, dt3)
# 基于数据库数据的日期偏移
def dateoffset(mydate, offsetday, offsettype):
cnxn = pyodbc.connect(xztApp_data_mssql_pyodbc_xtool)
cursor = cnxn.cursor()
cursor.execute("""select * from t_general_tradedate ORDER BY date DESC""")
myfetch = cursor.fetchall()
cursor.close()
cnxn.close()
listlen = len(myfetch)
if mydate > myfetch[0][0].strftime("%Y%m%d") or mydate < myfetch[listlen - 1][0].strftime("%Y%m%d"):
return '日期超出范围'
for dayi in range(listlen):
if myfetch[dayi][0].strftime("%Y%m%d") == mydate:
nowdayindex = dayi
break
mycount = 0
if offsetday > 0:
if offsettype == 1:
for dayi in range(1, listlen):
if nowdayindex - dayi < 0:
return '日期超出范围'
else:
if myfetch[nowdayindex - dayi][2] == 1:
mycount = mycount + 1
if mycount == abs(offsetday):
return myfetch[nowdayindex - dayi][0].strftime("%Y%m%d")
else:
if nowdayindex + offsetday < 0:
return '日期超出范围'
else:
return myfetch[nowdayindex - offsetday][0].strftime("%Y%m%d")
elif offsetday < 0:
if offsettype == 1:
for dayi in range(1, listlen):
if nowdayindex + dayi > listlen - 1:
return '日期超出范围'
else:
if myfetch[nowdayindex + dayi][2] == 1:
mycount = mycount + 1
if mycount == abs(offsetday):
return myfetch[nowdayindex + dayi][0].strftime("%Y%m%d")
else:
continue
else:
if nowdayindex + offsetday > listlen - 1:
return '日期超出范围'
else:
return myfetch[nowdayindex - offsetday][0].strftime("%Y%m%d")
elif offsetday == 0:
return myfetch[nowdayindex][0].strftime("%Y%m%d")
周几
def get_week_day(date):
week_day_dict = {
0: '星期一',
1: '星期二',
2: '星期三',
3: '星期四',
4: '星期五',
5: '星期六',
6: '星期天',
}
day = date.weekday()
return week_day_dict[day]
a = get_week_day(datetime.datetime.now())
print(a)
虚拟环境
# 切换
# cd C:\Python36
# 创建虚拟
# python -m venv myenv
# 激活虚拟环境
# .\myenv\Scripts\activate
# 可以安装Flask
# pip install Flask
# 停止
# deactivate