我是靠谱客的博主 朴素酒窝,这篇文章主要介绍通过python创建一个日期维度表1.要求,现在分享给大家,希望可以做个参考。

1.要求

3月份,是从2月21日~3月20日,也就是上月21日~当月20日

想要的结果数据:

 2.python代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import pymysql from datetime import datetime, date, timedelta # 导包的时候应该导 python-dateutil 这个包、否者报错 from dateutil.relativedelta import relativedelta # 使用python连接mysql数据库,并对数据库添加数据的数据的操作 # 创建连接,数据库主机地址 数据库用户名称 密码 数据库名 数据库端口 数据库字符集编码 conn = pymysql.connect(host='****', user='****', password='****', database='****', port=3306, charset='utf8') print("连接成功") # 创建游标 cursor = conn.cursor() # 添加一条数据数据 def insertdata1(): insert_emp_sql = "insert into dim_consignor_belong (id,consignor,belong_manager,is_count,user_id,company_id) values (199, '陕西泛海贸易有限公司', '朱朝忠', 1, 22272, 142)" # 执行语句 cursor.execute(insert_emp_sql) # 提交数据 conn.commit() # 批量添加数据 def insertdata2(): insert_emp_sql = "insert into dim_ahy_manager_date_time (date_time,month_name) values ('{}','{}');" # 指定时间的(datetime类型) y = datetime.strptime('2020-01-01', '%Y-%m-%d') # 插入1000条数据 for i in range(2000): # 对datetime的时间增加 date_time = (y + timedelta(days=+i)).strftime("%Y-%m-%d") date_month = (y + timedelta(days=+i)).strftime("%Y-%m") # 得到当月21号的时间 boundary_date = date_month + '-21' # 得到当月的下一个月的时间 month_date = ((y + timedelta(days=+i)) + relativedelta(months=1)).strftime("%Y-%m") # 如果日期下于当月的21号,插入的是当月的月份。 否则的话、插入下个月的月份。 if (date_time < boundary_date): print(date_time,date_month) ins_sql = insert_emp_sql.format(date_time, date_month) cursor.execute(ins_sql) conn.commit() else: print(date_time, month_date) ins_sql = insert_emp_sql.format(date_time, month_date) cursor.execute(ins_sql) conn.commit() # 获取当月的第一天 # _first_day = (y + timedelta(days=+i)).replace(day=1) # 关闭游标跟连接 def closeconn(): # 关闭游标 cursor.close() # 关闭连接 conn.close() # try: # insertdata1() insertdata2() # except: # conn.rollback() closeconn()

3.重点

主要是如何指定日期得到datetime类型的日期

如果对日期增加天

如果对日期增加月

最后

以上就是朴素酒窝最近收集整理的关于通过python创建一个日期维度表1.要求的全部内容,更多相关通过python创建一个日期维度表1内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部