TIL: time travel with Python’s standard library

til

There are a few different approaches for writing tests for date and/or time-sensitive functionality.  One could choose to add a sleep() in the test, which would guarantee that the time passed, but that also has the downside of increasing the run time of the test. Another option is to reach out to external libraries or packages but Python’s standard library already supports some “time travel”  functionality with the datetime module.

>>> import datetime

>>> datetime.date.today() datetime.date(2023, 2, 28)

>>> datetime.datetime.now()
datetime.datetime(2023, 2, 28, 12, 35, 16, 123614)

We can use a string format to make these outputs a little friendlier:

>>> datetime.date.today().strftime("%Y-%m-%dT%H:%M:%SZ")
'2023-02-28T00:00:00Z'

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
'2023-02-28T12:36:48Z'

For the “time travel” part we will use “timedelta”:

>>> search_time = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%Y-%m-%dT%H:%M:%SZ")

>>> search_time
'2023-02-28T12:41:48Z'

Check out the official documentation for other supported parameters for timedelta. 

Happy time travelling!


If you found this helpful, please share this article!

The post TIL: time travel with Python’s standard library was originally published at flaviabastos.ca

Related Posts