Not able to output datetime to text view in Ui.
Forgive my lack of understanding here as I have only been learning python for about a week now, but you said I was using 2 different variables to define ‘timecard’ but wouldn’t a list be an object and not a variable? Anyways, I’m pretty much dead in the water here because I get what I am looking for in the console however the actual text view itself isnt displaying anything. This is the code I have right now.
import datetime import appex, ui oTime = datetime.datetime.now() timecard =  def clock_in(sender): timecard.append(oTime) timecard.append('Clock in successful.') def clock_out(sender): timecard.append(oTime) timecard.append('Clock out successful.') def updateTextView(sender): v = sender.superview v['textview1'] = timecard(0,len) print (sender.text) v = ui.load_view() v.present('sheet')
I didn’t even notice, thank you! Still no luck however.
cvp last edited by cvp
@meleyz If I correctly understand what you want...
import ui import datetime import appex, ui def oTime(): return format(datetime.datetime.now()) timecard =  def clock_in(sender): timecard.append(oTime()) timecard.append('Clock in successful.') updateTextView() def clock_out(sender): timecard.append(oTime()) timecard.append('Clock out successful.') updateTextView() def updateTextView(): t = '' for line in timecard: t = t + line + '\n' v['textview1'].text = t v = ui.load_view() v.present('sheet')
Wow! Exactly! I have to say that this forum has become my new favorite place. Thank you for being so helpful. I can tell I still have much to learn just by looking at how you wrote the same script that I was trying to write only much more tidy (and it actually works). If I may ask, how long have you been writing code and can you offer any advice as far as a newbie such as myself learning code? I am trying to start with the basics but I find some concepts to be slightly confusing (such as trying to understand the concept of everything being an object). I have always been ‘computer savvy’ but Pythonista is the first and only coding experience I have ever had and I am really enjoying it thus far. I appreciate all the effort that has gone into building such a wonderful support system. Thank you again.
cvp last edited by
@meleyz I write code since years but not a lot in object oriented programming languages.
I'm really not very good in Python and I've written this little script not as I would do for me but trying to follow your directions.
But, in this forum, there are people like @JonB and @zrzka for the technical aspects, like @ccc for an help about nice Python, like @Phuket2 for telling you how to learn Python...
This is not a complete list, there are here a lot of marvelous guys, always ready to help you with real skills.
@meleyz, not to confuse you but datetime is not the easiest modules to work with. Especially as things get a little more complicated. I am doing some things with dates and times at the moment. I am using a module called arrow. The arrow module ships with Pythonista, but the docs for arrow are not built into Pythonista's help file. You can see the docs here. Again, I dont want to confuse you. But there are a number of modules that have been written as replacements/wrappers to the datetime module to simplify working with dates and times. I can see you usage at the moment is quite modest, but you might want to start adding extra functionality.
I also love this forum. Very nice place, a lot of nice guys.
cvp last edited by
@meleyz if you define the same action "clock" to both buttons, you can use this shorter code
import ui import datetime def clock(sender): v['textview1'].text = v['textview1'].text + 'Clock ' + sender.title + ': ' + format(datetime.datetime.now()) + '\n' v = ui.load_view() v.present('sheet')```
Thanks! I was actually wondering that myself, about shortening the code that is. And thank you @Phuket2 for the information and documentation link. I have been trying to absorb as much of the documentation as I can and not just assume that it doesn’t explain things. I’ve noticed several posters mention that the documentation falls short however I have noticed that the documentation is actually quite thorough if you take the time to read and really try to comprehend what it is saying. I will definitely take your advice on the functionality aspect and I am also trying to build good habits when writing code (such as proper format and leaving myself comments to remember what I am doing). This is how the code looks now and I am currently researching how to change the datetime output format to improve user friendliness. @cvp I will shorten the codes on the button functions when I get home from work. Thanks again.
import ui import datetime import appex import ui # import the proper modules needed to run script def oTime(): return format(datetime.datetime.now()) timecard =  # define a funtion to return the current time and create a container (list) to store current time when buttons are tapped def clock_in(sender): timecard.append(oTime()) timecard.append('Clock in successful.') updateTextView() def clock_out(sender): timecard.append(oTime()) timecard.append('Clock out successful.') updateTextView() # define funtions for button actions. Note that the funtion call to 'oTime' def updateTextView(): t = '' for line in timecard: t = t + line + '\n' v['textview1'].text = t # update the textview with the container created in the first function v = ui.load_view() v.present('sheet') # load the UI
I found the Arrow module to be much easier to use and the documentation was very helpful. I have updated my code using it. Thanks!
def oTime(): return arrow.now().format('MMMM DD, YYYY, h:m:s a')
@meleyz , thats great. When it starts getting very useful is when you have to start worrying about about time zones. In this case it appears that time zones are not important for you. From what I have read and seen etc, the best strategy if you are saving date/times is to save them in utc format (timeoffset +0). Then when you need to display your datetime (arrow object) convert the utc time to your time zone. It's a few extra steps, but arrow makes it very easy.
You have the utc = arrow.utcnow() method and the utc.to('Asia/Bangkok') or utc.to('local') methods. You can also use the utc.for_json() method or str(utc) to write the arrow object datetime as a string to your text file. When you read the text back in you can use the utc = arrow.get(datetime_text_from_file).
Maybe this comment seems over the top. If this is the only thing you every do with datetimes , then it probably is. But if you plan to work with dates and times more, from what I can see the safest bet is only ever save utc times and then convert them into the appropriate Timezone.
Maybe others disagree, not sure. But I find dates and times find there way into projects many times. Good to have a std approach and one will work on web servers etc. Imagine you call arrow.now() on a server somewhere in the world. The result could be anything depending on the servers settings.
Again, i just bring it up as it was something I struggled with when I was/am working with dates and times.
I think you answered one of my questions before I even had a chance to ask it. And no it is not over the top it is exactly the type of information I am looking for so thank you! I am trying to add a switch to the UI to change between 24 hour format and regular format however I am getting a type error ‘must be str not function ‘ and I am a little confused. Perhaps I am calling the function incorrectly of I have not used the proper statement. I have tried a for statement as well as a while loop and am seeing 2 different errors. The one I just described and a positional argument error on the oTime function. I will comment in the code which line is returning the type error.
import ui import arrow import appex import ui # import the proper modules needed to run script a = arrow.now().format('MMMM DD,YYYY, h:m:s a') b = arrow.now().format('MMMM DD, YYYY, HH:mm:ss A') def oTime(self): while oTime(self): return (a) else: return (b) timecard =  # define a funtion to return the current time and create a container (list) to store current time when buttons are tapped def clock_in(sender): timecard.append(oTime) timecard.append('Clock in successful.') updateTextView() def clock_out(sender): timecard.append(oTime) timecard.append('Clock out successful.') updateTextView() # define funtions for button actions. Note that the funtion call to 'oTime' def updateTextView(): t = '' for line in timecard: t = t + line + '\n' # this line is returning the type error must be str not function v['textview1'].text = t # update the textview with the container created in the first function v = ui.load_view() v.present('sheet') # load the UI
oTime is a function. Thus, append(oTime) is trying to append a function. You want append( oTime() ).
Of course, your oTime function is going to tive you some infinite recursion problems!
@meleyz, I think the below should help. No need to make 2 instances of the arrow object. Also the formatting can be applied in different parts of your code, depending what makes sense for you. In your case, really you dont need the function oTime. As you did in your code you can call the method in place.
Also your calls to timecard.append(oTime) should be timecard.append(oTime()). You are calling a function, so you need to add the ().
But the timecard.append could look like
timecard.append(arrow.now().format('MMMM DD,YYYY, h:m:s a') or using a _fmt1 for example based on a variable
import arrow _fmt1 = 'MMMM DD,YYYY, h:m:s a' _fmt2 = 'MMMM DD, YYYY, HH:mm:ss A' def oTime(fmt=None): # if no fmt param supplied, return the str version of the arrow # oject, otherwise return the formatted version return arrow.now().format(fmt) if fmt else str(arrow.now()) ''' while oTime(self): return (a) else: return (b) ''' print(oTime()) print(oTime(_fmt1)) print(oTime(_fmt2))
A more complete example
import ui import arrow class MyClass(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.lb = None self.sw = None self.fmts = ['MMMM DD,YYYY, h:m:s a', 'MMMM DD, YYYY, HH:mm:ss A'] self.make_view() self.update() self.update_interval = 1 def make_view(self): # create label lb = ui.Label(width=self.width, height=32, alignment=ui.ALIGN_CENTER) self.lb = lb self.add_subview(self.lb) # create switch sw = ui.Switch(action=self.update) sw.y = lb.frame.max_y + 10 sw.x = 10 self.sw = sw self.add_subview(sw) def update(self, sender=None): ''' int(self.sw.value) coerce False/True to 0 or 1 ''' self.lb.text = str(arrow.now().format(self.fmts[int(self.sw.value)])) if __name__ == '__main__': f = (0, 0, 300, 400) v = MyClass(frame=f, bg_color='white') v.present(style='sheet')
Can you see any obvious reason why the switch isn’t working? I believe I have everything written right (as much as I can see anyways) and the function name is in the ui switch, yet nothing happens when I tap the switch. It only returns
b_fmt2and I can’t figure out why. I’m sure it’s something I should’ve seen by now but anyways, here is my current code.
import ui import arrow import appex # import the proper modules needed to run script timecard =  a_fmt1 = 'MMMM DD,YYYY, h:m:s a' b_fmt2 = 'MMMM DD, YYYY, HH:mm:ss A' def switch_1(fmt): while fmt: return arrow.now().format(a_fmt1) else: return arrow.now().format(b_fmt2) def clock(sender): v['textview1'].text = v['textview1'].text + 'Time ' + sender.title + ': ' + str(switch_1('')) + '\n' v = ui.load_view() v.present('sheet') # load the UI
Can you explain what you think the purpose of
If that is your switch method, fmt is the sender, not a fmt, and will always return True in a while statement. You used that pattern before, you may want to review how while works too...
Phuket2 last edited by Phuket2
@meleyz , I have some hesitation about what I am posting below. Not sure it will help or confuse you.
Because the view is not complex, this would be a lot more easily done in a Custom ui class as I did above. But you keep using the while clause. Not sure why, maybe you think that your values will get continuously updated? They wont. You could stay in a while loop in there, but normally you would not want to.
But you can see in the Custom ui.View, it has a update method. The frequency it gets called depends on the update_interval attr
import ui import arrow import appex # import the proper modules needed to run script timecard =  a_fmt1 = 'MMMM DD,YYYY, h:m:s a' b_fmt2 = 'MMMM DD, YYYY, HH:mm:ss A' def create_view(**kwargs): ''' Create a view as I dont have the pyui file ''' v = ui.View(frame=(0, 0, 0, 220), **kwargs) lb = ui.Label(name='textview1', frame=(0,0,0,v.height), flex='W', alignment = ui.ALIGN_CENTER) sw = ui.Switch(name='switch_1', action=switch_1) v.add_subview(lb) v.add_subview(sw) sw.y = lb.frame.max_y + 10 sw.x = 10 # note here v is the main view, its superview property will be None return v # the action for the switch def switch_1(sender): sv = sender.superview if sender.value: sv['textview1'].text = arrow.now().format(a_fmt1) else: sv['textview1'].text = arrow.now().format(b_fmt2) # while is a loop construct. Also, you will not get a return value. # when action method is called you need to do some assigmentsin this case. # what maybe troubling you is getting a refence to your label object in # this method. ui.Views have a property called superview. Is the object the # view has been added to (it could be None). So we can get the sender # superview and access your other views as above as each ui.View also has a # list of all its subviews. ''' while fmt: return arrow.now().format(a_fmt1) else: return arrow.now().format(b_fmt2) ''' ''' def clock(sender): v['textview1'].text = v['textview1'].text + 'Time ' + sender.title + ': ' + str(switch_1('')) + '\n' ''' #v = ui.load_view() - Create the view instead a do not have the pyui file f = (0, 0, 320, 260) v = create_view(bg_color = 'white') # call the switch action, but in this case we need the switch object also switch_1(v['switch_1']) v.present('sheet') # load the UI
Thank you both for explaining. It has become clear that I misunderstood some of the documentation and have since spent time rereading those documents. I have the code working the way I need it to now however, I have one last question. I was getting the error
‘’str’ object has no attribute ‘superview’’until I deleted and re added the switch in the ui designer. Was that just a random bug or does that happen frequently with the ui designer? Thanks again for all the help.
That error means that you sent a string to your callback, rather than a view.
I'd bet when you were calling
It is usually helpful to look at, and paste the full traceback, to see where errors occured.
If the ui debugger pops up, you can actually look at the variables at each level of scope, and see where the problem happened, and can walk up the call chain to see where things were called. Pressing Print Traceback prints a full traceback, which is what you should always include whenever you are asking for help on the forum.
Learning to debug is a important skill, since it means you will be able to diagnose most problems without the delay of forum posting back and forth. (Thats why i was trying to ask leasing questions, rather than post a solution). If I can offer a few suggestions for effective debugging:
First, find out what line threw the exception. That's key, since if you don't know where the error is, how can you fix it. Printing the traceback will tell you this, and the sequence of function calls that got you to that point.
Next, make sure you understand what the error is telling you. AttributeErrors mean you tried to access an attribute that doesn't exist. Usually that means the object you have is not the one you expected -- for instance, when switch_1 is called with a string, instead of as ui.Switch.
Often the pythonista debugger will then let you walk up and down the stack, and examine variables in simple structures. Expand the window, then click on variables tto examine variable values. The switch to the stack view, and you can swicth to the callers scope, and look at variables in that scope, etc. The pythonista debugger is somewhat limited (cannot evaluate arbitrary expressions), but is easy to use and for every one of your problems here would have provided good insight.
As a crude, but easy and effective debugging technique, add print statements at key places in the code before your error. For instance, if you had print(fmt) in your old code, you would have noticed that you were being sent a ui.Switch, and not a boolean or string. If you are getting an AttributeError on
print(somevariable), print(type(somevariable)), and print(dir(somevariable))can help you understand what you are dealing with.
Eventually, you will want to learn how to use
pdb.pm()for debugging problems after the fact, or
pdb.settrace()for setting breakpoints. This is a slightly more advanced topic, but only sort of -- when I was learning python, after the basics, one of the first things i taught myself was the debugger!