omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    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

    Pythonista
    6
    39
    23311
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • dvader9
      dvader9 last edited by

      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

      1 Reply Last reply Reply Quote 0
      • dvader9
        dvader9 last edited by

        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.

        1 Reply Last reply Reply Quote 0
        • ccc
          ccc last edited by

          To post code to this forum, see: http://omz-forums.appspot.com/pythonista/post/5493027686580224

          1 Reply Last reply Reply Quote 0
          • ccc
            ccc last edited by

            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')
            
            1 Reply Last reply Reply Quote 0
            • dvader9
              dvader9 last edited by

              @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.

              1 Reply Last reply Reply Quote 0
              • KevinKarney
                KevinKarney last edited by

                Brilliant.
                Thanks dvader9 and @ccc. I knew it would be easy!
                Best wishes, Kevin

                1 Reply Last reply Reply Quote 0
                • abushama
                  abushama last edited by ccc

                  i need to extract and append in csv file???
                  MyScript

                  def 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()
                  
                  Phuket2 JonB 2 Replies Last reply Reply Quote 0
                  • Phuket2
                    Phuket2 @abushama last edited by

                    @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 docs

                    def 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})
                    
                    abushama 1 Reply Last reply Reply Quote 0
                    • ccc
                      ccc last edited by ccc

                      This post is deleted!
                      1 Reply Last reply Reply Quote 0
                      • JonB
                        JonB @abushama last edited by JonB

                        @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...

                        abushama 1 Reply Last reply Reply Quote 2
                        • abushama
                          abushama @Phuket2 last edited by

                          @Phuket2
                          i think u got my point
                          but when i ran the code
                          this kide or error pop up

                          AttributeError: '_ui.DatePicker' object has no attribute 'year'
                          which is:-
                          year=date.year

                          Phuket2 1 Reply Last reply Reply Quote 0
                          • abushama
                            abushama @JonB last edited by

                            @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😔

                            1 Reply Last reply Reply Quote 0
                            • Phuket2
                              Phuket2 @abushama last edited by Phuket2

                              @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.

                              abushama 2 Replies Last reply Reply Quote 0
                              • abushama
                                abushama @Phuket2 last edited by ccc

                                @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 with

                                import 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')
                                
                                1 Reply Last reply Reply Quote 0
                                • abushama
                                  abushama @Phuket2 last edited by

                                  @Phuket2
                                  As u notice that i got 2 open files to append
                                  the data of
                                  Amm and the date which i got from calender celnder

                                  all i need is to make it one open file
                                  which i can append in one csv file to covert to excel sheet

                                  ?????

                                  Phuket2 2 Replies Last reply Reply Quote 0
                                  • Phuket2
                                    Phuket2 @abushama last edited by

                                    @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='')	
                                    
                                    abushama 1 Reply Last reply Reply Quote 0
                                    • abushama
                                      abushama @Phuket2 last edited by

                                      @Phuket2
                                      am trying to post a screenshot of my UI but i dont know how??
                                      may u send my ur email plz?

                                      Phuket2 1 Reply Last reply Reply Quote 0
                                      • ccc
                                        ccc last edited by ccc

                                        Posting images to this forum works like this: https://guides.github.com/features/mastering-markdown/#examples

                                        1 Reply Last reply Reply Quote 1
                                        • Phuket2
                                          Phuket2 @abushama last edited by

                                          @abushama, I had already done this before I seen @ccc post. But this also should help

                                          1 Reply Last reply Reply Quote 1
                                          • ccc
                                            ccc last edited by ccc

                                            Perhaps the missing magic in this thread is seek() which lets you open a file in 'a' mode and then seek to the beginning of that file (append_file.seek(0, 0)) so that you can read() its contents and then seek to the end of the file (append_file.seek(0, 2)) and then write() new content to the end of the file.

                                            Phuket2 1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post
                                            Powered by NodeBB Forums | Contributors