# [Python-ideas] datetime.timedelta literals

Pål Grønås Drange paal.drange at gmail.com
Sat Jun 2 08:21:50 EDT 2018

```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

chrono::duration:

In C++ 14 the std::chrono::duration was introduced which corresponds
somewhat to
datetime.timedelta.

C++ 14 introduced so-called chrono literals[1], 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
microseconds

If a literal was interpreted as a datetime.timedelta, the following would
work
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
expected)

(D(hours=2.5) - D(minutes=14) + D(milliseconds=9300)) * 2
# datetime.timedelta(0, 16338, 600000)

Notes:

* C++ uses `min` instead of `m`.  `min` is a keyword in Python.
* In C++, `1d` means the first day of a month [2].
* In C++, `1990y` means the year 1990 (in the Proleptic Gregorian calendar)
[3].
* C++ have the types signed integers and not floats, so 2.5h would not be
valid.
* My apologies if this has been discussed before; my search-fu gave me
nothing.

References:

[1] std::literals::chrono_literals::operator""min
http://en.cppreference.com/w/cpp/chrono/operator%22%22min

[2] http://en.cppreference.com/w/cpp/chrono/day

[3] http://en.cppreference.com/w/cpp/chrono/year

Best regards,
Pål Grønås Drange
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180602/faaeac3b/attachment.html>
```