Python 日期范围查询

标签 python python-3.x pandas datepicker

我正在修改一个现有的应用程序,该应用程序查询数据库并返回过去 7 天的信息。我已经合并了一个日历应用程序,以便人们可以选择自己的日期进行查询。

日历运行良好

import tkinter as Tkinter
import tkinter.font as tkFont
import tkinter.ttk as ttk
import ttkcalendar
import pandas as pd
import numpy as np
import tkSimpleDialog  
from datetime import date

class CalendarDialog(tkSimpleDialog.Dialog):
    """Dialog box that displays a calendar and returns the selected date"""

    def body(self, master):
        self.calendar = ttkcalendar.Calendar(master)
        self.calendar.pack()

    def apply(self):
        self.result1 = self.calendar.selection
        self.result2 = self.calendar.selection

class CalendarFrame(Tkinter.LabelFrame):

    def __init__(self, parent):
        Tkinter.LabelFrame.__init__(self, parent, text="Choose Dates")

    def getbegindate():
        cd = CalendarDialog(self)
        self.result1 = cd.result1
        self.Begin_date.set(self.result1.strftime("%m/%d/%Y")) 

    def gettodate():
        cd = CalendarDialog(self)
        self.result2 = cd.result2
        self.To_date.set(self.result2.strftime("%m/%d/%Y"))

    self.Begin_date = Tkinter.StringVar()
    self.To_date = Tkinter.StringVar()

    def get_date():
        end = self.result2.strftime("%m/%d/%Y")
        start = self.result1.strftime("%m/%d/%Y")
        end1 = self.result2.strptime(end, "%m/%d/%Y").date()
        start1 = self.result1.strptime(start, "%m/%d/%Y").date() 
        delta = (end1 - start1).days
        daterange = [pd.date_range(start, end)]
        for single_date in daterange:
            x = single_date.strftime("%m/%d/%Y")
        rundate = x
        print(rundate) 

    Tkinter.Button(self, text="From date", command=getbegindate).grid(column=0, row=0)
    Tkinter.Entry(self, textvariable=self.Begin_date).grid(column=1, row=0)
    Tkinter.Entry(self, textvariable=self.To_date).grid(column=1, row=1)
    Tkinter.Button(self, text="To date", command=gettodate).grid(column=0, row=1)
    Tkinter.Button(self, text="SUBMIT", command=get_date).grid(column=0, columnspan=3)

def main():
    root = Tkinter.Tk()
    root.wm_title("Pick1")
    root.geometry("250x150+100+100")
    CalendarFrame(root).grid()
    root.mainloop()

if __name__ == "__main__":
    main()

回溯 7 天后,weeklyrpt 仍然可以正常工作。

选择日期范围后,它将返回“无”并返回未填充的屏幕。如何从日历 (Pick1.py) 获取日期来填充我的查询

app_window = tk.Tk()
app_window.withdraw()

def rundate():
    result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?")
    # result = tkinter.messagebox.askyesno()
    if result == True:
        rundate = date.today() - timedelta(7)
        return rundate
    else:
        os.system("pick1.py")
        def get_date():
                end = self.result2.strftime("%m/%d/%Y")
                start = self.result1.strftime("%m/%d/%Y")
                daterange = [pd.date_range(start, end)]
                for single_date in daterange:
                    x = single_date.strftime("%m/%d/%Y")
                rundate = x
                return rundate

rundate = rundate()
print(rundate)

# Query permits made effective since rundate
query = '''select `NPDES_ID`, `EffectiveDate`, `FacilityName`, `StateFacilityID`, `City`, `CountyName`
        from Permits 
        where `EffectiveDate` >= ?
        order by `NPDES_ID`'''

IDS=[]
FacCodes=[]
PermStrings=[]
PayStrings=[]
OwnerStrings=[]
MTB=[]
MTG=[]
MTR=[]
SWC=[]
MT0=[]
count=0
# for each row in result of query
for row in cur.execute(query, (rundate, )):
    try:
        d= row[1].strftime('%m/%d/%Y')
    except:
        d=""
    # create a display string with the appropriate information permit # - date -  facility name - city, county
    for i in range(len(row)):
            if not row[i]:
            row[i] = ""

    permitstring=row[0]+" | "+d+"\t | "+row[2]+"\t | "+row[4]+", "+row[5]+" County"
    IDS.append(row[0])
    tempid=row[0]
    # add the index to the appropriate permit type array, used to display seperately
    if tempid[0:3]=="MTB":
        MTB.append(count)
    if tempid[0:3]=="MTG":
        MTG.append(count)
    if tempid[0:4]=="MTR0":
        MTR.append(count)
    if tempid[0:3]=="MT0" or tempid[0:3]=="MT4" or tempid[0:3]=="MTX":
        MT0.append(count)
    if tempid[0:4]=="MTR1":
        SWC.append(count)
    FacCodes.append(row[3])
    PermStrings.append(permitstring)
    count+=1

这是一个相当大的应用程序,所以我希望包含重要的部分来看看我失败的地方

最佳答案

我修复了你的代码,现在它可以工作了,但我会尽可能少地进行更改以使其正常工作。大多数问题都是由类和面向对象编程的错误使用引起的。所以我认为如果我为你重写整个程序不会有任何帮助,但我认为你应该自己学习Python中的OOP编程。您可以在这些页面上找到一些基础知识( learnpythontutorialspointintrotopython ),或者只需输入 google,您就会找到很多页面、视频、类(class)等。

这是固定代码:

import pick1  ## This import line you need so you can use code from that file

app_window = tk.Tk()
#app_window.withdraw()              ## we use these three lines below because we only want to hide
app_window.geometry("1x1+0+0")      ##  tkinter window temporarily and withdraw() method causes
app_window.overrideredirect(True)   ##  the window to beforgotten about by the window manager
app_window.transient()             ## more details on https://wiki.tcl.tk/3175


def rundate():
    result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?")
    #result = messagebox.askyesno(title="Rundate", message="back 7 days?")

    # result = tkinter.messagebox.askyesno()
    if result == True:
        rundate = date.today() - timedelta(7)
        return rundate
    else:
        #os.system("pick1.py")
        #root = tkinter.Tk()
        app_window.wm_title("Pick1")
        app_window.geometry("250x150+100+100")
        app_window.overrideredirect(False)
        #app_window.mainloop()
        cm = pick1.CalendarFrame(app_window)
        cm.grid()
        ## here we wait until user has selected data range and
        ## and rundate has been calculated
        app_window.wait_variable(cm.wait_for_result)
        return cm.rundate

## we don't need this function because there is already same function in file pick1.py 
##        def get_date():
##            end = self.result2.strftime("%m/%d/%Y")
##            start = self.result1.strftime("%m/%d/%Y")
##            daterange = [pd.date_range(start, end)]
##            for single_date in daterange:
##                x = single_date.strftime("%m/%d/%Y")
##            rundate = x
##            return rundate



rundate = rundate()
print(rundate)

# Query permits made effective since rundate
query = '''select `NPDES_ID`, `EffectiveDate`, `FacilityName`, `StateFacilityID`, `City`, `CountyName`
        from Permits 
        where `EffectiveDate` >= ?
        order by `NPDES_ID`'''

IDS=[]
FacCodes=[]
PermStrings=[]
PayStrings=[]
OwnerStrings=[]
MTB=[]
MTG=[]
MTR=[]
SWC=[]
MT0=[]
count=0
# for each row in result of query
for row in cur.execute(query, (rundate, )):
    try:
        d= row[1].strftime('%m/%d/%Y')
    except:
        d=""
    # create a display string with the appropriate information permit # - date -  facility name - city, county
    for i in range(len(row)):
        if not row[i]:
            row[i] = ""

    permitstring=row[0]+" | "+d+"\t | "+row[2]+"\t | "+row[4]+", "+row[5]+" County"
    IDS.append(row[0])
    tempid=row[0]
    # add the index to the appropriate permit type array, used to display seperately
    if tempid[0:3]=="MTB":
        MTB.append(count)
    if tempid[0:3]=="MTG":
        MTG.append(count)
    if tempid[0:4]=="MTR0":
        MTR.append(count)
    if tempid[0:3]=="MT0" or tempid[0:3]=="MT4" or tempid[0:3]=="MTX":
        MT0.append(count)
    if tempid[0:4]=="MTR1":
        SWC.append(count)
    FacCodes.append(row[3])
    PermStrings.append(permitstring)
    count+=1

pick1.py 的代码:

import tkinter as Tkinter
import tkinter.font as tkFont
import tkinter.ttk as ttk
import ttkcalendar
import pandas as pd
import numpy as np
import tkSimpleDialog  
from datetime import date

class CalendarDialog(tkSimpleDialog.Dialog):
    """Dialog box that displays a calendar and returns the selected date"""

    def body(self, master):
        self.calendar = ttkcalendar.Calendar(master)
        self.calendar.pack()

    def apply(self):
        self.result1 = self.calendar.selection
        self.result2 = self.calendar.selection

class CalendarFrame(Tkinter.LabelFrame):

    def __init__(self, parent):
        Tkinter.LabelFrame.__init__(self, parent, text="Choose Dates")
        self.parent = parent
        self.Begin_date = Tkinter.StringVar()
        self.To_date = Tkinter.StringVar()
        self.wait_for_result = Tkinter.IntVar() ## we will use this variable to wait for user to select date range
        Tkinter.Button(self, text="From date", command=self.getbegindate).grid(column=0, row=0)
        Tkinter.Entry(self, textvariable=self.Begin_date).grid(column=1, row=0)
        Tkinter.Entry(self, textvariable=self.To_date).grid(column=1, row=1)
        Tkinter.Button(self, text="To date", command=self.gettodate).grid(column=0, row=1)
        Tkinter.Button(self, text="SUBMIT", command=self.get_date).grid(column=0, columnspan=3)


    def getbegindate(self):
        cd = CalendarDialog(self)
        self.result1 = cd.result1
        self.Begin_date.set(self.result1.strftime("%m/%d/%Y")) 

    def gettodate(self):
        cd = CalendarDialog(self)
        self.result2 = cd.result2
        self.To_date.set(self.result2.strftime("%m/%d/%Y"))

    #self.Begin_date = Tkinter.StringVar()
    #self.To_date = Tkinter.StringVar()

    def get_date(self):
        end = self.result2.strftime("%m/%d/%Y")
        start = self.result1.strftime("%m/%d/%Y")
        # I commented this lines below because they don't have any use
        #end1 = self.result2.strptime(end, "%m/%d/%Y").date()
        #start1 = self.result1.strptime(start, "%m/%d/%Y").date() 
        #delta = (end1 - start1).days
        daterange = [pd.date_range(start, end)]
        for single_date in daterange:
            x = single_date.strftime("%m/%d/%Y")
        self.rundate = x
        self.wait_for_result.set(1)     # now we have result so we can set variable wait_for_result to 1
        print(self.rundate)
        self.parent.destroy()        # I added this line so tkinter window disappears once when user clicks SUBMIT button

    #Tkinter.Button(self, text="From date", command=getbegindate).grid(column=0, row=0)
    #Tkinter.Entry(self, textvariable=self.Begin_date).grid(column=1, row=0)
    #Tkinter.Entry(self, textvariable=self.To_date).grid(column=1, row=1)
    #Tkinter.Button(self, text="To date", command=gettodate).grid(column=0, row=1)
    #Tkinter.Button(self, text="SUBMIT", command=get_date).grid(column=0, columnspan=3)

关于Python 日期范围查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49451501/

相关文章:

python - imaplib/gmail 如何在不标记已读的情况下下载完整邮件(所有部分)

python - 登录模块 - Python

python - NameError : name 'DEFAULT_STRING' is not defined

python - pandas 使用 groupby 填充

python - 如何通过 Python 获取特定类别的平均值

python - pandas——将数据追加到系列中,同时增加日期时间索引

python - pip 安装的 uWSGI ./python_plugin.so 错误

Python 日志记录问题?

python - 设置 mod_python 解释器

python - 在 Python 中格式化驱动器