Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Extracting the Date from the UI date and time spinner
-
I am new to Python but have progressed as far as getting a complex algorithm coded, but I am now struggling with the UI interface. I have a button which when pressed should read the date from the date spinner.
The code for the button is...
def GetDate(sender):
thisdate = sender.superview['DatePicker']But I cannot see how to get year, month, day from this date
H E L PBest regards and thanks in advance
Kevin -
Kevin,
I have not used the date picker object yet, but based on the help files - for DatePicker objects and for datetime.datetime class -, I'm guessing the following syntax for your button action could be used:
def GetDate(sender): date = sender.superview['DatePicker1'] # assuming that is the name of your DatePicker object # this returns a datetime.datetime object, see module datetime year = date.year month = date.month # etc... For day, hour, minute and so forth.
Dave
-
Apologies for the lack of clarity in the code. This is my first time posting a code snippet in this forum, and I don't know why some of the carriage returns did not go through.
-
To post code to this forum, see: http://omz-forums.appspot.com/pythonista/post/5493027686580224
-
import ui my_date = None def date_picker_action(sender): my_date = sender.date print(my_date) view = ui.View() date_picker = ui.DatePicker() date_picker.action = date_picker_action view.add_subview(date_picker) view.present('sheet')
-
@ccc thanks for the link to posting code on the forum. I've edited my response above, though the code you posted conveys the idea in a more complete example.
-
Brilliant.
Thanks dvader9 and @ccc. I knew it would be easy!
Best wishes, Kevin -
i need to extract and append in csv file???
MyScriptdef calndr(sender): date = sender.superview['calender'] # assuming that is the name of your DatePicker object # this returns a datetime.datetime object, see module datetime year = date.year month = date.month with open('newfile.csv',"a") as f: newfileWriter=csv.writer(f) newfileWriter.writerow([calndr()]) tarDate=calndr(targetDate['calender']) f.close()
-
@abushama , I have never used the csv lib before. But I think the below should work. I basically copied it from the examples in the csv documentation.
There are other types of writers, but i came across the dict writer, which seems it would be a good choice anyway. link to csv docsdef calndr(sender): date = sender.superview['calender'] # assuming that is the name of your DatePicker object # this returns a datetime.datetime object, see module datetime year = date.year month = date.month with open('newfile.csv', 'a') as csvfile: fieldnames = ['Year', 'Month'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'Year': year, 'Month': month})
-
This post is deleted! -
@abushama You seem to be calling calndr() from within calndr(). calndr() does not return a date.
Reread each line in your code and remind yourself what you are trying to achieve with each line... -
@Phuket2
i think u got my point
but when i ran the code
this kide or error pop upAttributeError: '_ui.DatePicker' object has no attribute 'year'
which is:-
year=date.year -
@JonB
i did but am still straggling
how to extract time from calnder celnder and write it in csv file
that all what am trying😔 -
@abushama. One proble was you were setting the date to be the ui.DatePicker, not the attr date. You can see I changed it in your function (I missed that originally, I didn't run the code because you didn't post it all, so it was easy for me to miss that). Look, I just got it working in the way i thought you had tried to get it working.
Your calndr function looks likes it would make more sense for you to put it into the class as a method.
I am often torn about how to help. If I make too many changes it can be frustrating to the person and confuse them more. @JonB point about going over your code is very valid. The way you where calling your function again inside trying to write to the csv file was way off. So I would suggest to take what i have done and try to move your calndr function into the class. Then really look closely about what's happening when you are writing out your csv file.
You are not that far away. Just take your time and really look through it. Still here if you need more help.
EDIT please see the notes I added to the bottom of the post.import ui import csv def calndr(sender): date = sender.superview['calender'].date # assuming that is the name of your DatePicker object # this returns a datetime.datetime object, see module datetime year = date.year month = date.month with open('newfile.csv', 'a') as csvfile: fieldnames = ['Year', 'Month'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'Year': year, 'Month': month}) class MyClass(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.make_view() def make_view(self): dtp = ui.DatePicker(name='calender') btn = ui.Button(width=80, height=32, border_width=.5, bg_color='white', corner_radius=.5, action=calndr) btn.title='Save' # just position the button btn.center = self.center btn.y = self.height - (btn.height * 2) # add the date picker & btn to the view self.add_subview(dtp) self.add_subview(btn) if __name__ == '__main__': f = (0, 0, 300, 400) v = MyClass(frame = f) v.present(style='sheet', animated=False)
Btw, the csv writer has other methods, for example to write out the headers to you file. Of course you would only want to write the headers once. Oh, I should have mentioned, you should not really move your calndr function into the class the way it is. It really should be a method that just is passed you year and month and writes out the csv file. You really don't want the other objects around. If you make the method just to handle the csv file, you could for example reuse that code in other objects.
-
@Phuket2
thank u very much
i got this one too i would like to share
and advice my
i kw this not like ur prof one u did but this what i came withimport ui import datetime import csv def calc(sender): v = sender.superview GontarHighPrice = v['txt1'].text GontarLowPrice = v['txt2'].text DollerRate =v ['txt3'].text Avg = (float(GontarHighPrice)+float(GontarLowPrice))/2 TonInPounds=22.25*Avg SPound="{0:,.2f}".format(TonInPounds) v['txt4'].text=str(SPound) TonInDollars=TonInPounds/float(DollerRate) v['txt5'].text=str("{0:,.2f}".format(TonInDollars)) #TID=v['txt5'].text ProtSudan=TonInDollars+150 v['txt6'].text="{0:,.2f}".format(ProtSudan) #FOB=v['txt6'].text C_F= ProtSudan+50 v['txt7'].text="{0:,.2f}".format(C_F) #CF=v['txt7'].text Amman= C_F+120 v['txt8'].text="{0:,.2f}".format(Amman) Amm=v['txt8'].text with open('newfile1.csv', 'a') as csvfile1: fieldnames = ['Amm'] writer = csv.DictWriter(csvfile1, fieldnames=fieldnames) writer.writerow({'Amm': Amm}) csvfile1.close() def calndr(sender): Mydate=sender.date day = Mydate.day month = Mydate.month year = Mydate.year with open('newfile1.csv', 'a') as csvfile1: fieldnames = ['Day', 'Month','Year'] writer = csv.DictWriter(csvfile1, fieldnames=fieldnames) writer.writerow({'Day': day, 'Month': month,'Year': year}) csvfile1.close() v = ui.load_view() v.present('sheet')
-
@Phuket2
As u notice that i got 2 open files to append
the data of
Amm and the date which i got from calender celnderall i need is to make it one open file
which i can append in one csv file to covert to excel sheet?????
-
@abushama, I am not really sure what your final result is suppose to look like. But if you look below there is a function that will take a dict and write it out to the csv file. So that function is only concerned with your csv file, not how to get the data. If you call the function over and over it will be ok, because we only write the headers out once.
import csv import os def write_to_csv(filename, data_dict): fexists = os.path.exists(filename) # We set a var to see if the file exists fieldnames = list(my_data_dict.keys()) # get a list of the keys to use as the header with open(filename, 'a') as csvfile: #fieldnames = ['Day', 'Month','Year'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # only write the header one time to the file if not fexists: writer.writeheader() writer.writerow(data_dict) #svfile1.close() # you dont need this. Look up Context Managers if __name__ == '__main__': filename = 'my_csv.csv' # you would collect your data and put it in a dict. my_data_dict = dict( Day = 1, Month = 12, Year = 2017, Amm = 2.5 ) write_to_csv(filename , my_data_dict) # just print the file to the console, make sure its what we wanted with open(filename) as f: for line in f: print(line, end='')
-
@Phuket2
am trying to post a screenshot of my UI but i dont know how??
may u send my ur email plz? -
Posting images to this forum works like this: https://guides.github.com/features/mastering-markdown/#examples
-