Conversion from calendar week to date
Sometimes one has to convert a date written as year, calendar week (CW), and day of week to an actual date with month and date. The behaviour in the begin/end of a year may be not straightforward. For example according to ISO 8601 monday date of the CW 1 year 2019 is 31 January 2018. As far as I can see there is no standard function for conversion in python.
I use the following hacky code:
|
|
It prints the week-based date to a string and then parses it using %V
and %u
format from python 3 (docs)
Therefore you don’t need to implement ISO logic of dates calculation. Hopefully such a funciton apppear in standard library.
Python 2 doesn’t have these %V
and %u
implemented. :(
Measuring elapsed time
Python standard library has a set of functions to measure elapsed time.
One can get information about each function using time.get_clock_info(name)
Clock | Adjustable | Monotonic | Resolution | Tick Rate |
---|---|---|---|---|
process_time | False | True | 1e-07 | 10,000,000 |
clock | False | True | 4.665306263360271e-07 | 2,143,482 |
perf_counter | False | True | 4.665306263360271e-07 | 2,143,482 |
monotonic | False | True | 0.015625 | 64 |
time | True | False | 0.015625 | 64 |
source of measurements: Python Clocks Explained, 2015.
time.perf_counter()
gives the most accurate results when testing the difference between two times and pretty fast.
timeit
uses time.perf_counter()
by default.
time.process_time()
can be helpful to understand how long different parts of a program took to run.
according to the PEP 0418, several modules use (or could use) time.monotonic(), including concurrent.futures, multiprocessing, queue, subprocess, telnet and threading modules to implement timeout.