Я новичок в Python. У меня есть полдюжины пользовательских финансовых приложений VB6, которые я унаследовал несколько лет назад.
Я начал работать с Python несколько месяцев назад и обнаружил \ построил средство выбора календаря, где при запуске он генерирует выбранную дату, и я могу напечатать ее в правильном формате '06 / 01/2019 '
В конце этого модуля я вызываю Импорт файла моего второго модуля GeeksGui.py, который запускает простой графический интерфейс, и когда я нажимаю на кнопку, он запускает мои SQL-запросы и генерирует нужные мне данные.
Я пытался использовать свою self.full_date из первого модуля на GeeksGui.py IN, во втором модуле есть SQL STEP 02 для Prod_DT, выбранный из даты Каландера, выбранной многими способами, показанными онлайн, и когда я помещаюв статическую дату второй модуль работает нормально, завершает работу и создает мои файлы, как и ожидалось.
Когда я вставляю «self.full_date» из первого модуля, это выдает мне ошибку формата даты ниже, я знаю, что она близка к работе и работает со статической датой, такой как '06 / 01/2019 ':
RESTART: C:\Users\m62305\AppData\Local\Programs\Python\Python37-32\Hanes_Pkg1\Hanes_Pkg1\PythonCalander.py
'7/01/2019'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\m62305\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ibm_db_dbi.py", line 1235, in _ set_cursor_helper
num_columns = ibm_db.num_fields(self.stmt_handler)
Исключение: сбой SQLNumResultCols: [IBM] [Драйвер CLI] [DB2] SQL0180N Синтаксис строкового представления значения даты и времени неверен.SQLSTATE = 22007 SQLCODE = -180
Ниже приведен первый код для модуля PythonCalander.py
###Please Excuse all my remarked attempts at working on stuff as I was learning as I was putting this together.
# ---------------------------------------------------------------------------
import calendar
import tkinter as tk
import time
from tkinter import ttk
##import builtins
#import Hanes_Pkg1.GeeksGui
class MyDatePicker(tk.Toplevel):
"""
Description:
A tkinter GUI date picker.
"""
def __init__(self, widget=None, format_str='%m-%d-%Y'):
"""
:param widget: widget of parent instance.
:param format_str: print format in which to display date.
:type format_str: string
Example::
a = MyDatePicker(self, widget=self.parent widget,
format_str='%02d-%s-%s')
"""
super().__init__()
self.widget = widget
self.str_format = format_str
self.title("Report Date")
self.resizable(0, 0)
self.geometry("+630+690")
self.init_frames()
self.init_needed_vars()
self.init_month_year_labels()
self.init_buttons()
self.space_between_widgets()
self.fill_days()
self.make_calendar()
def init_frames(self):
self.frame1 = tk.Frame(self)
self.frame1.pack()
self.frame_days = tk.Frame(self)
self.frame_days.pack()
def init_needed_vars(self):
self.month_names = tuple(calendar.month_name)
self.day_names = tuple(calendar.day_abbr)
self.year = time.strftime("%Y")
self.month = time.strftime("%B")
self.month1 = time.strftime("%m")
####BELOW WORKED MNTH1
#print(self.month1)
#print(self.month.strftime("%m"))
########print(self.month_names)
def init_month_year_labels(self):
self.year_str_var = tk.StringVar()
self.month_str_var = tk.StringVar()
# print(self.month_str_var )
self.year_str_var.set(self.year)
self.year_lbl = tk.Label(self.frame1, textvariable=self.year_str_var,
width=3)
self.year_lbl.grid(row=0, column=5)
self.month_str_var.set(self.month)
self.month_lbl = tk.Label(self.frame1, textvariable=self.month_str_var,
width=8)
self.month_lbl.grid(row=0, column=1)
#print(self.month_str_var)
def init_buttons(self):
self.left_yr = ttk.Button(self.frame1, text="←", width=5,
command=self.prev_year)
self.left_yr.grid(row=0, column=4)
self.right_yr = ttk.Button(self.frame1, text="→", width=5,
command=self.next_year)
self.right_yr.grid(row=0, column=6)
self.left_mon = ttk.Button(self.frame1, text="←", width=5,
command=self.prev_month)
self.left_mon.grid(row=0, column=0)
self.right_mon = ttk.Button(self.frame1, text="→", width=5,
command=self.next_month)
self.right_mon.grid(row=0, column=2)
def space_between_widgets(self):
self.frame1.grid_columnconfigure(3, minsize=40)
def prev_year(self):
self.prev_yr = int(self.year_str_var.get()) - 1
self.year_str_var.set(self.prev_yr)
self.make_calendar()
def next_year(self):
self.next_yr = int(self.year_str_var.get()) + 1
self.year_str_var.set(self.next_yr)
self.make_calendar()
def prev_month(self):
index_current_month = self.month_names.index(self.month_str_var.get())
index_prev_month = index_current_month - 1
# index 0 is empty string, use index 12 instead,
# which is index of December.
if index_prev_month == 0:
self.month_str_var.set(self.month_names[12])
else:
self.month_str_var.set(self.month_names[index_current_month - 1])
self.make_calendar()
def next_month(self):
index_current_month = self.month_names.index(self.month_str_var.get())
try:
self.month_str_var.set(self.month_names[index_current_month + 1])
except IndexError:
# index 13 does not exist, use index 1 instead, which is January.
self.month_str_var.set(self.month_names[1])
########print((self.month_names[1]))
self.make_calendar()
def fill_days(self):
col = 0
# Creates days label
for day in self.day_names:
self.lbl_day = tk.Label(self.frame_days, text=day)
self.lbl_day.grid(row=0, column=col)
col += 1
def make_calendar(self):
# Delete date buttons if already present.
# Each button must have its own instance attribute for this to work.
try:
for dates in self.m_cal:
for date in dates:
if date == 0:
continue
self.delete_buttons(date)
except AttributeError:
pass
year = int(self.year_str_var.get())
month = self.month_names.index(self.month_str_var.get())
self.m_cal = calendar.monthcalendar(year, month)
self.x =(month)
#print(x)
# build dates buttons.
for dates in self.m_cal:
row = self.m_cal.index(dates) + 1
for date in dates:
col = dates.index(date)
if date == 0:
continue
self.make_button(str(date), str(row), str(col))
########################3print(date)
def make_button(self, date, row, column):
"""
Description:
Build a date button.
:param date: date.
:type date: string
:param row: row number.
:type row: string
:param column: column number.
:type column: string
"""
exec(
"self.btn_" + date + " = ttk.Button(self.frame_days, text=" + date
+ ", width=5)\n"
"self.btn_" + date + ".grid(row=" + row + " , column=" + column
+ ")\n"
"self.btn_" + date + ".bind(\"<Button-1>\", self.get_date)"
)
####prints all days in the month####print(date)
def delete_buttons(self, date):
"""
Description:
Delete a date button.
:param date: date.
:type: string
"""
exec(
"self.btn_" + str(date) + ".destroy()"
)
def get_date(self, clicked=None):
"""
Description:
Get the date from the calendar on button click.
:param clicked: button clicked event.
:type clicked: tkinter event
"""
###TEST###
clicked_button = clicked.widget
year = self.year_str_var.get()
month = self.month_str_var.get()
date = clicked_button['text']
#################################print(month)
self.full_date = self.str_format % (self.x, date, year)
#print(date)
###############teststart=self.month1, date, year
###print('teststart!!')
##############print(self.month1, date, year)
#print (teststart)
# print(self.full_date)
#start_date=self.full_date
######################################################builtins.foo= self.full_date
print(self.full_date)
globvar = self.full_date
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = self.full_date
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar()
# Replace with parent 'widget' of your choice.
try:
self.widget.delete(0, tk.END)
self.widget.insert(0, self.full_date)
except AttributeError:
pass
# def f():
# print (s)
#s = (self.full_date)
#f()
import Hanes_Pkg1.GeeksGui
##print(dir(Hanes_Pkg1.GeeksGui))
if __name__ == '__main__':
def application():
MyDatePicker(format_str="'%s/%02d/%s'")
root = tk.Tk()
btn = tk.Button(root, text="Report Month", command=application)
#btn1 = tk.Button(root, text="Run Query", command=application)
#self.query_button.configure(command=self.sendQuery)
#self.query_button = Button (window, text="Send Query")
#self.query_button.grid(row=self.current_row,column=0,columnspan=2)
btn.pack()
root.mainloop()
Вот мой код для второго модуля GeeksGui.py:
import PythonCalander
#####################print(PythonCalander.full_date)
#from Hanes_Pkg1.Hanes_Pkg1.PythonCalander import self
#print(month)
#print(PythonCalander.self.full_date)
from tkinter import *
from PythonCalander import *
window = Tk()
window.title("ADVICE Custom Reporting App")
window.geometry('350x200')
lbl = Label(window, text="Welcome")
lbl.grid(column=0, row=0)
def clicked():
import builtins
#builtins.foo = PythonCalander.self.full_date
import pickle as pick
import pandas as pd
pd.set_option('display.max_rows', 10000)
pd.set_option('display.max_columns', 10000)
pd.set_option('display.width', 10000)
import ibm_db
ibm_db_conn = ibm_db.connect("db2","xyz","xyz")
import ibm_db_dbi
conn = ibm_db_dbi.Connection(ibm_db_conn)
##STEP01 BELOW***
df123=pd.read_sql("SELECT DISTINCT b.brnch_cd, b.BRNCH_NM \
FROM ggna.acct a inner join ggna.brnch b on a.client_key=b.client_key \
WHERE a.acct_num=('0000000') ",conn)
strucref = pd.read_csv('C:/python/Hanesbrands Structure Reference.csv')
#strucref=strucref.ACCT_NUM = strucref.ACCT_NUM.str.strip()
#strucref=strucref.BRNCH_CD = strucref.BRNCH_CD.str.strip()
export_csv = df123.to_csv (r'C:\Python\export_dataframe_HANESBRANDS_STEP_01.csv', index = None, header=True)
export_csv = strucref.to_csv (r'C:\Python\export_datafraame_HANESBRANDS_strucref_table.csv', index = None, header=True)
####STEP02 BELOW###
####################REMEMBER to always use a prior months date when testing this #####
df123a=pd.read_sql("SELECT a.acct_num, d.svc_dt, c.brnch_cd, e.subscrbr_emp_id, e.relshp_cd, d.IN_NT_AMT, d.OUT_NT_AMT,\
FROM abc.acct a inner join bcd.struc_key_trnsltn b ON a.acct_KEY = b.acct_key and a.client_key = b.client_key INNER JOIN \
on b.brnch_KEY = c.brnch_key and b.client_key = c.client_key INNER JOIN ghi.rpt_membr_clm d on b.struc_key_trsln_id \
INNER JOIN xyz. WHERE a.acct_num=('0000000') and d.prod_dt = ('self.full_date') \
and d.IN_NT_AMT + d.OUT_NT_AMT + d.DRUG_AMT + d.CAP_AMT != 0",conn)
##export_csv = df123.to_csv (r'C:\Python\export_dataframe009.csv', index = None, header=True)
#####works##df1234=df123.groupby(['ACCT_NUM']).sum()
###*****7791 rows RETURN DO NOT MODIFY THIS ONE BELOW...##
#print(df123a)
df1234=df123a.groupby(['ACCT_NUM','SVC_DT','BRNCH_CD','SUBSCRBR_EMP_ID','RELSHP_CD']).sum().reset_index()
#print(df1234)
#df12345= df1234['SUBSCRBR_EMP_ID'.str.strip()
df1234.ACCT_NUM = df1234.ACCT_NUM.str.strip()
df1234.BRNCH_CD = df1234.BRNCH_CD.str.strip()
df1234.SUBSCRBR_EMP_ID = df1234.SUBSCRBR_EMP_ID.str.strip()
##0820_2019#########
df1234['SUBSCRBR_EMP_ID'] = df1234['SUBSCRBR_EMP_ID'].astype(str).str[:-2]
#df1234.info()
###########STEP03####
import pickle as pick
import pandas as pd
pd.set_option('display.max_rows', 500000)
pd.set_option('display.max_columns', 500000)
pd.set_option('display.width', 500000)
import ibm_db
ibm_db_conn = ibm_db.connect("db2w","q028","TRIumph7")
import ibm_db_dbi
conn = ibm_db_dbi.Connection(ibm_db_conn)
df123=pd.read_sql("SELECT a.acct_num, a.svc_beg_dt, c.ssn, a.brnch_cd, b.rel_cd , a.elg_amt, a.inelg_amt,
df1234=df123.groupby(['ACCT_NUM','SVC_BEG_DT','BRNCH_CD','SSN','REL_CD']).sum().reset_index()
df1234.BRNCH_CD = df1234.BRNCH_CD.str.strip()
#and sum_hra(df123,df123.elg_amt + df123.INELG_AMT + df123.FINANC_CRD_FEE_AMT + df123.OTHER_AMT)"
#######, a.elg_amt, a.inelg_amt, a.FINANC_CRD_FEE_AMT, a.OTHER_AMT
#and sum_frame_by_column(df123,'hra_sum', ['elg_amt','inelg_amt','FINANC_CRD_FEE_AMT', 'OTHER_AMT'])",conn)
export_csv = df1234.to_csv (r'C:\Python\export_datafraame_HANESBRANDS_STEP_03.csv', index = None, header=True)
###9-5-2019 working in a merge the dataframes step required***
#df_new = pd.concat([df1234, df123])
#df_new
#export_csv = df_new.to_csv (r'C:\Python\export_datafraame_HANESBRANDS_STEPS_MERGED.csv', index = None, header=True)
#print(df_new)
####test=pd.merge(df1234, df123, on= df1234.SUBSCRBR_EMP_ID = df123.SSN)
#test=pd.merge(df1234, df123, left_on='SUBSCRBR_EMP_ID', right_on='SSN')
#export_csv = test.to_csv (r'C:\Python\export_datafraame_HANESBRANDS_STEPS_MERGED.csv', index = None, header=True)
lbl.configure(text="Reports Are Running !!")
lbl.configure(text="Reports Have Completed !!")
btn = Button(window, text="Create Reports", command=clicked)
btn.grid(column=1, row=0)
####BELOW new OK button to close it out****
#ok = Tk.Button(self.parent, width=5, text='OK', command=self.kill_and_save)
#self.wid.append(ok)
#ok.grid(row=9, column=2, columnspan=3, pady=10)
#def kill_and_save(self):
#self.parent.destroy()
window.mainloop()
Заранее большое спасибо