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 "<stdin>", line 1, in <module>
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

Reply via email to