Python date and time countdown list in plural

I am trying to create a function that lists the time between dates using the correct words, in particular, I want it to take into account the plural. I know that I can do this by running all the numbers and if the expression, but I really hoped to find a more effective way to achieve my goal.

IE: I want to return 221 days, 1:17:06.996068from datetimeas 221 days, 1 hour, 17 minutes, and 6.99 seconds.. It is important that it indicates the day / hour / minute / second or days / hours / minutes / seconds when necessary.

An example of my code snippet for working with:

from datetime import datetime as dt

now = dt.now(tz=None) # Current local computer time
test = dt(2018,3,25,23,0,0) # March 25th, 2018 23h 0m 0s
countdown = test - now
print(countdown) # 2 days, 1:45:00.685739
# Desired outcome: 2 days, 1 hour, 45 minutes, 0.68 seconds.

Is there any function that works effectively between exceptional or multiple time?

+4
source
3

, "":

def pl(number,unit):
    return unit + "s" if number > 1 or isinstance(number, float) else unit 

pl(10, "hour")
#'hours'
pl(.75, "sec")
#'secs'

if .

+2

pluralize, .

from datetime import datetime as dt
from collections import OrderedDict

def pluralize(amount, unit):
    if amount != 1:
        unit += 's'
    return '{} {}'.format(amount, unit)

def format_delta(tdelta):
    d = OrderedDict()

    d["day"] = tdelta.days
    d["hour"], rem = divmod(tdelta.seconds, 3600)
    d["minute"], d["second"] = divmod(rem, 60)

    return ', '.join(pluralize(v, k) for k, v in d.items() if v != 0)

now = dt.now(tz=None) # Current local computer time
test = dt(2018,3,25,23,0,0) # March 25th, 2018 23h 0m 0s
countdown = test - now

format_delta(countdown) # '1 day, 22 hours, 13 minutes, 1 second'

, , , StackEchange.

. , , dict.

plurals = {
    'maximum': 'maxima',
    'index': 'indices',
    'bar': 'baz'
}

def pluralize(amount, unit):
    if amount != 1:
        unit = plurals.get(unit, unit + 's')
    return '{} {}'.format(amount, unit)

pluralize(2, 'maximum') # '2 maxima'
pluralize(2, 'cake') # '2 cakes'
+1

, , , :

def pluralize(s, count):
  if count > 1 or count == 0 or count < -1:
    return s + "s"
  else:
    return s

Then the key understanding is to understand that you have two lists of the same size: the first is a data set, the second is a set of labels for the data. This is an ideal precedent for the combinator zip()! This combinator takes two lists (for example: [1,2,3], [4,5,6]) and combines them into one list of pairs (for example: [1,4], [2,5], [3, 6 ].)

xs = [1, 12, 1, 46]
ys = ["day", "hour", "minute", "second"]
zs = map(lambda x: [x[0], pluralize(x[1], x[0])], zip(xs,ys))

Then in zsyou get:

> print(list(zs))
> [[1, 'day'], [12, 'hours'], [1, 'minute'], [46, 'seconds']]

What you can use to create a user-submitted string.

+1
source

Source: https://habr.com/ru/post/1695269/


All Articles