Re: [Python] Stampare oggetti timedelta

2022-02-18 Per discussione Marco Giusti

On 17.02.2022 16:40, Gabriele Battaglia wrote:

Ciao.

Per stampare a video un oggetto ottenuto da un'operazione fra date, a
parte la manipolazione manuale che posso fare con i suoi valori,
esiste un metodo già pronto per personalizzarne la visualizzazione?

Cioè print o str, danno già qualcosa di leggibile ma se volessi
personalizzare la formattazione come si fa con strptime, è possibile?



Non sembra che gli oggetti di tipo timedelta supportino il la sintassi
per la formattazione di stringhe[1]. E' possibile comunque di create una
classe ad-hoc per questo. Spero che quanto segue sia leggibile:

$ python
Python 3.10.2 (main, Feb 15 2022, 12:33:54) [GCC 10.2.1 20210110] on 
linux
Type "help", "copyright", "credits" or "license" for more 
information.

>>> import datetime
>>> yesterday_now = datetime.datetime.now() - 
datetime.timedelta(days=1)

>>> now = datetime.datetime.now()
>>> now - yesterday_now
datetime.timedelta(days=1, seconds=4, microseconds=951695)
>>> (now - yesterday_now).total_seconds()
86404.951695
>>> delta = (now - yesterday_now)
>>> format(delta, 'S')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported format string passed to 
datetime.timedelta.__format__

>>> class TimeDeltaFormat:
...  def __init__(self, timedelta):
...   self.delta = timedelta
...  def __format__(self, format_spec):
...   if format_spec == '':
...return str(self.delta)
...   elif format_spec == 'd':
...return str(self.delta.days)
...   elif format_spec == 's':
...return str(self.delta.seconds)
...   elif format_spec == 'm':
...return str(self.delta.microseconds)
...   elif format_spec == 'S':
...return str(self.delta.total_seconds())
...   else:
...raise TypeError("unsupported format string")
...
>>> delta_f = TimeDeltaFormat(delta)
>>> format(delta_f, 's')
'4'
>>> format(delta_f, 'S')
'86404.951695'
>>> print(f"{delta_f:s}.{delta_f:m}")
4.951695
>>> delta.microseconds
951695
>>>

[1] https://docs.python.org/3/library/string.html#format-string-syntax

___
Python mailing list
Python@lists.python.it
https://lists.python.it/mailman/listinfo/python


Re: [Python] R: Registri modbus

2022-02-18 Per discussione Vinny Mautone
Scusa potresti spiegarmelo ho visto che hai usato le operazioni sui bit su
questo sono un po scarso o se puoi indicarmi una guida abbastanza semplice
per capire questo tipo di operazioni ho letto qualcosa ma mi risulta sempre
complicato
Grazie

Il Gio 17 Feb 2022, 17:32 Alessandro T.  ha scritto:

> On 17/02/22 07:34, Vinny Mautone wrote:
> > Studiando un pò sono riuscito a scrivere questa funzione che fa il suo
> > dovere, ma volevo capire se era la strada giusta o si potesse
> > velocizzare un po, comunque questa è la funzione
> >
> > def reg_to_string(reg):
> > s = ''
> > for ele in reg:
> > if ele:
> > b = format(ele, '016b')  # converto il registro da decimale in binario
> > ch = chr(int(b[:8], 2))  # prendo i primi 8 bit e li converto in char
> > if ch.isalnum():  # controllo che sia un numero o una lettera
> > s += ch  # lo aggiungo alla stringa
> > ch = chr(int(b[8:], 2))  # faccio la stessa cosa con gli altri 8 bit
> > if ch.isalnum():
> > s += ch
> > return s  # ritorno la stringa
> >
> > Grazie per eventuali correzioni o miglioramenti
> >
>
>
> reg = [21070, 12601, 12340, 12593, 12593, 13312]
>
> versione compatta:
> s = ''.join(c for r in reg for i in (1,0) if (c:=chr(r >> 8*i &
> 0xff)).isalnum())
>
>
> versione estesa:
> s = []
> for r in reg:
>for i in (1,0):
>  c = chr(r >> 8*i & 0xff)
>  if c.isalnum():
>s.append(c)
> s = ''.join(s)
>
> --
> Alessandro T.
>
> R: Perché leggiamo dall'alto al basso e da sinistra a destra.
> D: Perché dovrei iniziare la risposta all'e-mail dopo il testo citato?
>
> ___
> Python mailing list
> Python@lists.python.it
> https://lists.python.it/mailman/listinfo/python
>
___
Python mailing list
Python@lists.python.it
https://lists.python.it/mailman/listinfo/python


Re: [Python] R: Registri modbus

2022-02-18 Per discussione
Il giorno gio 17 feb 2022 alle ore 17:32 Alessandro T.
 ha scritto:
>
> reg = [21070, 12601, 12340, 12593, 12593, 13312]
>
> versione compatta:
> s = ''.join(c for r in reg for i in (1,0) if (c:=chr(r >> 8*i &
> 0xff)).isalnum())

oppure anche

```
>>> "".join(chr(n) for d in reg for n in divmod(d, 256) if n != 0)
'RN19044'
```

㎝

--
 THE 🍺-WARE LICENSE (Revision ㊷):
<㎝🐌🐍.🇮🇹> wrote this 📧. As long as you retain this notice you can
do whatever you want with this stuff. If we meet some day, and you
think this stuff is worth it, you can buy me a 🍺 in return. — ㎝
___
Python mailing list
Python@lists.python.it
https://lists.python.it/mailman/listinfo/python