[Python-ideas] datetime.timedelta literals
Robert Vanden Eynde
robertve92 at gmail.com
Sat Jun 2 09:08:51 EDT 2018
2.5*h - 14*min + 9300*ms * 2
h = timedelta(hours=1)
min = timedelta (minutes=1)
ms = timedelta (milliseconds=1)
By the way "min" isn't a keyword, it's a standard function so it can be
used as a variable name.
However why be limited to time units ? One would want in certain
application to define other units, like meter ? Would we want a litteral
for that ?
For units like those, the "*" operator works well, and if one want more
support (like, mix minutes and seconds) one could write simple classes or
use libraries, for example to avoid to add time and distance units.
Le sam. 2 juin 2018 à 14:21, Pål Grønås Drange <paal.drange at gmail.com> a
> Elevator pitch:
> (2.5h - 14min + 9300ms).total_seconds()
> # 8169.3
> from datetime import datetime as dt
> start = dt.now()
> end = dt.now()
> (end-start) < 5s
> # True
> In C++ 14 the std::chrono::duration was introduced which corresponds
> somewhat to
> C++ 14 introduced so-called chrono literals, which are literals
> specified as
> [number][h|min|s|ms|us|ns], e.g.
> * 2.5h
> * 14min
> * 9300ms
> These literals should correspond to
> * datetime.timedelta(0, 9000) # 2.5h = 2.5*3600 = 9000 seconds
> * datetime.timedelta(0, 840) # 14min = 14*60 = 840 seconds
> * datetime.timedelta(0, 9, 300000) # 9300ms = 9 seconds + 3*10^5
> If a literal was interpreted as a datetime.timedelta, the following would
> out of the box:
> 2.5h - 14min + 9300ms * 2
> which would correspond to
> from datetime import timedelta as D
> D(hours=2.5) - D(minutes=14) + D(milliseconds=9300) * 2
> # datetime.timedelta(0, 8178, 600000) # (*2 precedes, so that's to be
> (D(hours=2.5) - D(minutes=14) + D(milliseconds=9300)) * 2
> # datetime.timedelta(0, 16338, 600000)
> * C++ uses `min` instead of `m`. `min` is a keyword in Python.
> * In C++, `1d` means the first day of a month .
> * In C++, `1990y` means the year 1990 (in the Proleptic Gregorian
> calendar) .
> * C++ have the types signed integers and not floats, so 2.5h would not be
> * My apologies if this has been discussed before; my search-fu gave me
>  std::literals::chrono_literals::operator""min
>  http://en.cppreference.com/w/cpp/chrono/day
>  http://en.cppreference.com/w/cpp/chrono/year
> Best regards,
> Pål Grønås Drange
> Python-ideas mailing list
> Python-ideas at python.org
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas