Page 1 of 1

zfill()

Posted: Fri Jul 30, 2021 10:29 pm
by njepsen
I am [UNSUCCESSFULLY] trying to add a leading zero to the dates and times in a time group. It seems that zfill is nat available in up.
How do I do this ?

Code: Select all


def local_dt():
   try:
             r = rtc.now()  #r= (2021, 7, 25, 10, 58, 46, 25361, None)
             year = r[0]
             year= str(year)
             month= r[1]
             month=str(month).zfill(2)
             day= r[2]
             day=str(day).zfill(2)
             min =r[4]
             min = str(min).zfill(2)
             hour = r[3]
             hour = str(hour).zfill(2)
             sec = r[5]
             sec = str(sec).zfill(2)
                         
             local_dt = day +'/'+ month +'/'+ year + ' '+ hour +':'+ min +'.'+ sec
             return local_dt
   except Exception as e:
       print('## local_dt failed',e)
## local_dt failed 'str' object has no attribute 'zfill'
Traceback (most recent call last):

Re: zfill()

Posted: Fri Jul 30, 2021 10:58 pm
by davef
Would:

Code: Select all

while (True):
    epoch = utime.time()
    local_time = utime.localtime(epoch)
    seconds = local_time[5]
    minutes = local_time[4]
    hours = local_time[3]
    day = local_time[2]
    month = local_time[1]
    year = local_time[0]


#  this is needed or else you get time = 14:6
    if ((minutes >= 0) and (minutes <= 9)):
        minutes = '0' + str(minutes)
    else:
        minutes = str(minutes)

#  this is needed or else you get time = 0:06
    if ((hours >= 0) and (hours <= 9)):
        hours = '0' + str(hours)
    else:
        hours = str(hours)

    time = hours + ':' + minutes #  time is a string
    date = str(year) + '-' + str(month) + '-' + str(day)

    print(str(seconds))
work in your situation?

Re: zfill()

Posted: Sat Jul 31, 2021 12:16 am
by njepsen
Hi Dave
yes that works, but I hoped there would be a more elegant 'format string to 2 digits' solution. I didnt use epoch because i have already set the RTC from my local ISP who gives me local time with daylight saving taken care of.
I'm about to post a question about sleep, light sleep and deep sleep, which you may care to help me on?

neil
Palmerston North.

Re: zfill()

Posted: Sat Jul 31, 2021 6:46 am
by JennaSys
str(sec).rjust(2, '0') would normally work too, but it looks like that's not implemented either. So you can use format():

Code: Select all

'{:02d}'.format(sec)
Or you can brute force some string manipulation:

Code: Select all

('00' + str(sec))[-2:]

Re: zfill()

Posted: Sat Jul 31, 2021 4:54 pm
by williamhenrick
I normally use the cascading

Code: Select all

('00' + str(sec))[-2:]