如何在 Python 中将 Days Duration 划分为更小的部分
Posted
技术标签:
【中文标题】如何在 Python 中将 Days Duration 划分为更小的部分【英文标题】:How to divide Days Duration into further smaller sections in Python 【发布时间】:2021-08-31 23:05:43 【问题描述】:'''
import pandas as pd
import pymysql as sql
import pygsheets
import datetime
#%%
today =datetime.date.today()
month=today.month
year =today.year
d =today.day
#%%
date =datetime.datetime.now().date() - pd.to_timedelta("90day")
date_filter =datetime.datetime.strftime(date,'%Y-%m-%d')
#%%
db = sql.connect(host = 'ffff',
user = 'aadsd',
password ='#######',
database = 'ewewewe')
cursor=db.cursor()
cursor.execute(f"""select * from table1 t1
left join table2 t2 on t1.id=t2.id
where t2.name ='xct' and date(addtime(t1.created_on,"05:30:00"))>date; """)
'''
我是 Python 新手,我已将最后一个单元格中的 date 定义为
日期 = datetime.datetime.now().date() - pd.to_timedelta("90day") ,
我想在另一个单元格中将 90 天部分拆分为前 45 天和下一个 45 天的概念,因为目前由于大量数据库记录,我面临“超出最大语句执行时间”错误的问题
【问题讨论】:
【参考方案1】:您可以使用它来将日期拆分为任意大小
import datetime
#%%
now = datetime.datetime.now()
date_filter =datetime.datetime.strftime(date,'%Y-%m-%d')
#%%
bin_size = 5
for i in range(90,0,-bin_size):
end_date = now.strftime('%Y-%m-%d')
start_date = now-datetime.timedelta(days=bin_size)
now = start_date
start_date = start_date.strftime('%Y-%m-%d')
print(f"""select * from table1 t1
left join table2 t2 on t1.id=t2.id
where t2.name ='xct' and date(addtime(t1.created_on,"05:30:00")) between start_date and end_date; """)
这样的结果
select * from table1 t1
left join table2 t2 on t1.id=t2.id
where t2.name ='xct' and date(addtime(t1.created_on,"05:30:00")) between 2021-06-11 and 2021-06-16;
select * from table1 t1
left join table2 t2 on t1.id=t2.id
where t2.name ='xct' and date(addtime(t1.created_on,"05:30:00")) between 2021-06-06 and 2021-06-11;
select * from table1 t1
left join table2 t2 on t1.id=t2.id
where t2.name ='xct' and date(addtime(t1.created_on,"05:30:00")) between 2021-06-01 and 2021-06-06;
...
如果您希望 sql 查询更快。如果可能,请将 date(addtime(t1.created_on,"05:30:00"))
替换为 t1.created_on
。
使用 python time shift 即更改 start_date 和 end_date 确实减少时间会更好。
【讨论】:
以上是关于如何在 Python 中将 Days Duration 划分为更小的部分的主要内容,如果未能解决你的问题,请参考以下文章
3.days.ago、2.hours.from_now 等没有 Rails?