DEV Community

DEV Community

John Mark Bulabos

Posted on Jun 10, 2023

How to Use Python to Time Travel: Exploring Datetime

Hold on to your keyboards, fellow time travelers! I bet you clicked on this title thinking, "Heck yeah, I want to see the dinosaurs!" Well, my dear chrono-naut, you’re not gonna see any T-Rexes today, but I guarantee a fun-filled adventure through the sands of time ( code time, that is) using Python’s datetime library. So, buckle up, grab your sonic screwdriver or DeLorean, and let’s dive into the Pythonic TARDIS!

First Stop: Importing the Time Machine (Datetime) 🚀

Let's start by summoning the time machine. How? By importing the datetime module, of course! This module is like the flux capacitor of your DeLorean – it's what makes time travel possible. Just don't hit 88 miles per hour, or who knows where you'll end up!

Journey to the Present 🎁

Are you ready to discover the secrets of the present time? This handy spell, I mean, method, will reveal the current date and time. Abracadabra!

Wow, this is heavy! But remember, "where we’re going, we don’t need roads."

Time-Traveling to the Past ⚔

Do you fancy a quick jaunt to the medieval times? Bring your suit of armor! Let's calculate what the date was exactly 500 years ago. Watch out for the Black Plague though. Yikes!

Who knew Python had such a rich history? Pun intended.

Whizzing into the Future 🚀

Next stop, the future! It's time to find out if we have hoverboards, flying cars, or if Python has finally reached version 4. Let’s jump 1000 years ahead!

Party like It’s 1999 (or Any Other Year) 🎉

Now let’s take control of the wheels. With the help of datetime , you can party in any year you desire! Just make sure to invite Prince.

Watch Your Step: Time Zones 🌍

Time zones are like the Bermuda Triangle of datetime. They can be confusing and make you feel lost. But fear not, for Python has a trusty GPS called pytz.

Just don’t ask Python what time it is on Mars. We’re still working on that.

Delorean Fuel is Running Low! ⛜

Alright, time travelers, our journey is nearing its end. But before we wrap up, let’s do some crazy math with dates. Like subtracting your birth date from today to find out how many days old you are. But beware, your age is going to be in days, not years, which might make you feel like a wise old wizard.

Save the Dates 📅

You might also want to store the dates you've collected on your travels. Python’s got your back with the ability to format dates and save them in a more human-readable form. Let’s say you want to save the exact date of when you discovered Pluto (let's pretend it's still a planet, just for the nostalgia).

Pitfalls and Wormholes đŸ•łïž

Disclaimer: Please remember that though we have gallivanted through time, there is one thing Python datetime won’t save you from: the Y10K problem, a.k.a. the Year 10,000 problem. Someday computers might not be able to handle a five-digit year. But let’s be real – that's a problem for the cyborgs of the future.

Moreover, always validate the date inputs, or you might accidentally cause a temporal paradox, and we all know how messy those can get!

Recap of Our Adventures 📜

As we prepare to park our Pythonic time machine, let’s do a quick recap:

  • We summoned the datetime time machine.
  • We zoomed through the present, past, and future.
  • We learned how to party in any year we desire.
  • We navigated the perilous waters of time zones.
  • We did some time wizardry with date math.
  • We found out how to save dates for posterity.
  • We peered into the ominous abyss of the Y10K problem.

What an adventure! I hope you had as much fun as I did. Remember to use your newfound time-traveling powers wisely and only for good. Also, if you meet your past self, minimal small talk is advised.

Now, for more adventures in coding, debugging, and maybe a little bit more time-travel, check out PAIton and Crossovers on YouTube. Don’t forget to hit that subscribe button! As Doc Brown would say, “Your future is whatever you make it, so make it a good one!”

Happy coding, Time Lords!

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

gedons profile image

  • Work Interkel Technologies
  • Joined Jan 10, 2023

Amazing Post!!!! Who knew i could travel to the future with python :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

jaloliddin0210 profile image

C# dasturlash tilida kasrlar

Jaloliddin Xolmirzayev - Apr 18

astrabert profile image

AI enthusiasm #4 - Your stable diffusion chatbot🐠

Astra Bertelli - Apr 13

sofiamurphy profile image

Why Flutter Teams up with Dart?

Sofia Murphy - Apr 18

dev3l profile image

Principles of Code - Five Key Points to Better Systems

Justin L Beall - Apr 14

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Delorean 1.0.0

pip install Delorean Copy PIP instructions

Released: Feb 7, 2018

library for manipulating datetimes with ease and clarity

Verified details

Maintainers.

Avatar for myusuf3 from gravatar.com

Unverified details

Project links, github statistics.

  • Open issues:

View statistics for this project via Libraries.io , or by using our public dataset on Google BigQuery

License: MIT License (MIT license)

Author: Mahdi Yusuf

Classifiers

  • OSI Approved :: MIT License
  • Python :: 2.6
  • Python :: 2.7
  • Python :: 3
  • Python :: 3.1
  • Python :: 3.3
  • Python :: 3.4
  • Python :: 3.5
  • Python :: 3.6

Project description

http://delorean.readthedocs.org/en/latest/_static/delorean.png

Delorean: Time Travel Made Easy

Delorean is a library for clearing up the inconvenient truths that arise dealing with datetimes in Python. Understanding that timing is a delicate enough of a problem delorean hopes to provide a cleaner less troublesome solution to shifting, manipulating, and generating datetimes .

Delorean stands on the shoulders of giants pytz and dateutil

Delorean will provide natural language improvements for manipulating time, as well as datetime abstractions for ease of use. The overall goal is to improve datetime manipulations, with a little bit of software and philosophy.

Pretty much make you a badass time traveller.

Getting Started

Here is the world without a flux capacitor at your side:

Now lets warm up the delorean :

Look at you looking all fly. This was just a test drive: check out out what else delorean can help with in the documentation .

Project details

Release history release notifications | rss feed.

Feb 7, 2018

Dec 9, 2015

Aug 4, 2015

Nov 17, 2014

Oct 15, 2014

Sep 13, 2014

May 7, 2014

Jan 21, 2014

Sep 24, 2013

Apr 28, 2013

Mar 16, 2013

Jan 24, 2013

Jan 23, 2013

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages .

Source Distribution

Uploaded Feb 7, 2018 Source

Hashes for Delorean-1.0.0.tar.gz

  • portuguĂȘs (Brasil)

Supported by

time machine travel python

Introducing time-machine, a New Python Library for Mocking the Current Time

The problem, libfaketime, time-machine.

Subscribe via RSS , Twitter , Mastodon , or email:

#245: Fire up your Python time machine (and test some code)

time machine travel python

Watch the live stream:

Watch this episode on YouTube

About the show

Sponsored by us:

  • Check out the courses over at Talk Python
  • And Brian’s book too !

Special guest: Juan Pedro Araque Espinosa (Youtube Chanel: Commit that Line )

Michael #1: State of the community (via Jet Brains)

  • This report presents the combined results of the fifth annual Developer Ecosystem Survey conducted by JetBrains
  • Not just Python, but all of us
  • Python is more popular than Java in terms of overall usage, while Java is more popular than Python as a main language.
  • The 5 fastest growing languages are Python, TypeScript, Kotlin, SQL, and Go.
  • A majority of the respondents (71%) develop for web backend.
  • Does fall into the trap of “Hi, I’m a CSS developer, nice to meet you” though
  • Women are more likely than men to be involved in data analysis, machine learning, and UX/UI design or research.
  • Women are less likely than men to be involved in infrastructure development and DevOps, system administration, or Deployment.

Brian #2: Cornell - record & replay mock server

  • Suggested by Yael Mintz (and it’s her project)
  • “Cornell makes it dead simple, via its record and replay features to perform end-to-end testing in a fast and isolated testing environment.
  • When your application integrates with multiple web-based services, end-to-end testing is crucial before deploying to production. Mocking is often a tedious task. It becomes even more tiresome when working with multiple APIs from multiple vendors.
  • vcrpy is an awesome library that records and replays HTTP interactions for unit tests. Its output is saved to reusable "cassette" files.
  • By wrapping vcrpy with Flask, Cornell provides a lightweight record and replay server that can be easily used during distributed system testing and simulate all HTTP traffic needed for your tests.”

Juanpe #3: Factory boy (with Pydantic by chance)

  • Factory_boy allows creating factories to generate objects that could be used as text fixtures
  • Briefly mentioned in the past in episode 193
  • A factory takes a base object and allows to very easily and naturally define default values for each field of the object.
  • One can have many factories for the same object that could be used define different types of fixtures of the same object
  • It works with ORM objects (Django, Mongo, SQLAlchemy
)
  • If you have a project that uses Pydantic to define your objects, factory boy also supports Pydantic although it is not documented and does it by a side effect
  • Internally factory boy generates a parameters dictionary that that is unpacked when constructing the model at hands. This works perfectly with pydantic and can be used to generate pydantic objects on the fly with the full power of factory boy

Michael #4: pyinstrument

  • Call stack profiler for Python. Shows you why your code is slow!
  • Instead of writing python script.py , type pyinstrument script.py
  • Your script will run as normal, and at the end (or when you press ^C ), Pyinstrument will output a colored summary showing where most of the time was spent.
  • Async support! Pyinstrument now detects when an async task hits an await, and tracks time spent outside of the async context under this await.
  • Pyinstrument also has a Python API. Just surround your code with Pyinstrument
  • Nice middleware examples for Flask & Django

Brian #5: Python 3.10 is now in Release Candidate phase. RC1 just released.

  • RC2 planned for 2021-09-06
  • official release is planned for 2021-10-04
  • It is strongly encourage maintainers of third-party Python projects to prepare their projects for 3.10 compatibility during this phase
  • PEP 623 -- Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.
  • PEP 604 -- Allow writing union types as X | Y
  • PEP 612 -- Parameter Specification Variables
  • PEP 626 -- Precise line numbers for debugging and other tools.
  • PEP 618 -- Add Optional Length-Checking To zip.
  • bpo-12782 : Parenthesized context managers are now officially allowed.
  • PEP 632 -- Deprecate distutils module.
  • PEP 613 -- Explicit Type Aliases
  • PEP 634 -- Structural Pattern Matching: Specification
  • PEP 635 -- Structural Pattern Matching: Motivation and Rationale
  • PEP 636 -- Structural Pattern Matching: Tutorial
  • PEP 644 -- Require OpenSSL 1.1.1 or newer
  • PEP 624 -- Remove Py_UNICODE encoder APIs
  • PEP 597 -- Add optional EncodingWarning

Juanpe #6: time-machine

  • Time-machine mock datetime and time related calls globally noticeably faster than other well known tools like freezgun.
  • The mocking is achieved by replacing the c-level calls by whatever value we want which means the library does not need to mock individual imports.
  • Mocking datetime cannot be done with patch.object and needs to be patched everywhere it is used which can turn mocking everything into a tedious (and/or slow) process.
  • Datetime methods (now, today, utcnow
) can be mocked by setting a frozen time or by letting the time tick since the mock call is made.
  • It provides a simple context manager to use it as well as pytest fixture that makes using it very simple from datetime import datetime import time_machine @time_machine.travel("2021-01-01 21:00") def test_in_the_past(): assert datetime.now() == datetime(2021, 1, 1, 21, 0) --------------------------------- # The time_machine fixture can also be used with pytest def test_in_the_past(time_machine): time_machine.move_to(datetime(2021, 1, 1, 21, 0)) assert datetime.now() == datetime(2021, 1, 1, 21, 0)
  • Credit-card stealing malware found in official Python repository and Software downloaded 30,000 times from PyPI ransacked developers’ machines (via Joe Riedly)
  • Flavors of TDD - Test & Code episode 162
  • Working on tox and CI chapter of 2nd edition of pytest book , hoping that to be released within the next week.

JavaScript Developer Bouncing from framework to framework

Want to go deeper? Check our projects

Course: Python for the Absolute Beginner course

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

travel-time-prediction

Here are 8 public repositories matching this topic..., lixus7 / time-series-works-conferences.

Time-Series Work Summary in CS Top Conferences (NIPS, ICML, ICLR, KDD, AAAI, WWW, IJCAI, CIKM, ICDM, ICDE, etc.)

  • Updated Apr 20, 2024

aptx1231 / Traffic-Prediction-Open-Code-Summary

Summary of open source code for deep learning models in the field of traffic prediction

  • Updated Nov 17, 2022

zouguojian / Travel-time-prediction

When Will We Arrive? A Novel Multi-Task Spatio-Temporal Attention Network Based on Individual Preference for Estimating Travel Time

  • Updated Jul 19, 2023

karthik-d / LocateMyBus

IoT and ML to assuage the uncertainty associated with city bus commute. Track live running status and avail tentative schedule of buses. Minimal IoT setup with a central ML-driven web-backend.

  • Updated Mar 24, 2024

khaled-alkilane / GSTA

GSTA: Gated Spatial-Temporal Attention Approach for Travel Time Prediction

  • Updated Oct 11, 2021
  • Jupyter Notebook

sn-lp / Dublin-Bus-Project-Team-14

Dublin Bus app developed as part of the MSc in Computer Science (Conversion) Summer Research Practicum.

  • Updated Nov 8, 2021

capibaro / divinetime

a flask web api for travel time estimation

  • Updated Jun 28, 2022

OleksiiKulahin / RoutePlanner

Application for planning and optimization of the routes in uncertain conditions. Helps to choose the best departure time for the specific route. Uses Bing Maps API.

  • Updated Jun 25, 2022

Improve this page

Add a description, image, and links to the travel-time-prediction topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the travel-time-prediction topic, visit your repo's landing page and select "manage topics."

  • By logging in you accept our terms of service and privacy policy

time-machine Release 2.14.1

Release 2.14.1 toggle dropdown 2.14.1 2.14.0 2.13.0 2.12.0 2.11.0 2.10.0 2.9.0 2.8.2 2.8.1 2.8.0.

Travel through time in your tests.

Homepage PyPI Python

Documentation

Time-machine.

https://img.shields.io/github/actions/workflow/status/adamchainz/time-machine/main.yml?branch=main&style=for-the-badge

A quick example:

For a bit of background, see the introductory blog post and the benchmark blog post .

Testing a Django project? Check out my book Speed Up Your Django Tests which covers loads of ways to write faster, more accurate tests. I created time-machine whilst writing the book.

Installation

Python 3.8 to 3.13 supported. Only CPython is supported at this time because time-machine directly hooks into the C-level API.

If you’re coming from freezegun or libfaketime, see also the below section on migrating.

travel(destination, *, tick=True)

travel() is a class that allows time travel, to the datetime specified by destination . It does so by mocking all functions from Python's standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager.

destination specifies the datetime to move to. It may be:

  • A datetime.datetime . If it is naive, it will be assumed to have the UTC timezone. If it has tzinfo set to a zoneinfo.ZoneInfo instance , the current timezone will also be mocked.
  • A datetime.date . This will be converted to a UTC datetime with the time 00:00:00.
  • A datetime.timedelta . This will be interpreted relative to the current time. If already within a travel() block, the shift() method is easier to use (documented below).
  • A float or int specifying a Unix timestamp
  • A string, which will be parsed with dateutil.parse and converted to a timestamp. If the result is naive, it will be assumed to be local time.

Additionally, you can provide some more complex types:

  • A generator, in which case next() will be called on it, with the result treated as above.
  • A callable, in which case it will be called with no parameters, with the result treated as above.

tick defines whether time continues to "tick" after travelling, or is frozen. If True , the default, successive calls to mocked functions return values increasing by the elapsed real time since the first call. So after starting travel to 0.0 (the UNIX epoch), the first call to any datetime function will return its representation of 1970-01-01 00:00:00.000000 exactly. The following calls "tick," so if a call was made exactly half a second later, it would return 1970-01-01 00:00:00.500000 .

Mocked Functions

All datetime functions in the standard library are mocked to move to the destination current datetime:

  • datetime.datetime.now()
  • datetime.datetime.utcnow()
  • time.clock_gettime() (only for CLOCK_REALTIME )
  • time.clock_gettime_ns() (only for CLOCK_REALTIME )
  • time.gmtime()
  • time.localtime()
  • time.monotonic() (not a real monotonic clock, returns time.time() )
  • time.monotonic_ns() (not a real monotonic clock, returns time.time_ns() )
  • time.strftime()
  • time.time()
  • time.time_ns()

The mocking is done at the C layer, replacing the function pointers for these built-ins. Therefore, it automatically affects everywhere those functions have been imported, unlike use of unittest.mock.patch() .

Usage with start() / stop()

To use independently, create an instance, use start() to move to the destination time, and stop() to move back. For example:

travel() instances are nestable, but you'll need to be careful when manually managing to call their stop() methods in the correct order, even when exceptions occur. It's recommended to use the decorator or context manager forms instead, to take advantage of Python features to do this.

Function Decorator

When used as a function decorator, time is mocked during the wrapped function's duration:

You can also decorate asynchronous functions (coroutines):

Beware: time is a global state - see below .

Context Manager

When used as a context manager, time is mocked during the with block:

Class Decorator

Only unittest.TestCase subclasses are supported. When applied as a class decorator to such classes, time is mocked from the start of setUpClass() to the end of tearDownClass() :

Note this is different to unittest.mock.patch() 's behaviour, which is to mock only during the test methods. For pytest-style test classes, see the pattern documented below .

Timezone mocking

If the destination passed to time_machine.travel() or Coordinates.move_to() has its tzinfo set to a zoneinfo.ZoneInfo instance , the current timezone will be mocked. This will be done by calling time.tzset() , so it is only available on Unix. The zoneinfo module is new in Python 3.8 - on older Python versions use the backports.zoneinfo package , by the original zoneinfo author.

time.tzset() changes the time module’s timezone constants and features that rely on those, such as time.localtime() . It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with its timezone.override() ).

Here’s a worked example changing the current timezone:

Coordinates

The start() method and entry of the context manager both return a Coordinates object that corresponds to the given "trip" in time. This has a couple methods that can be used to travel to other times.

move_to(destination, tick=None)

move_to() moves the current time to a new destination. destination may be any of the types supported by travel .

tick may be set to a boolean, to change the tick flag of travel .

For example:

shift(delta)

shift() takes one argument, delta , which moves the current time by the given offset. delta may be a timedelta or a number of seconds, which will be added to destination. It may be negative, in which case time will move to an earlier point.

pytest plugin

time-machine also works as a pytest plugin. It provides a function-scoped fixture called time_machine with methods move_to() and shift() , which have the same signature as their equivalents in Coordinates . This can be used to mock your test at different points in time and will automatically be un-mock when the test is torn down.

If you are using pytest test classes, you can apply the fixture to all test methods in a class by adding an autouse fixture:

escape_hatch

The escape_hatch object provides functions to bypass time-machine. These allow you to call the real datetime functions, without any mocking. It also provides a way to check if time-machine is currently time travelling.

These capabilities are useful in rare circumstances. For example, if you need to authenticate with an external service during time travel, you may need the real value of datetime.now() .

The functions are:

  • escape_hatch.is_travelling() -> bool - returns True if time_machine.travel() is active, False otherwise.
  • escape_hatch.datetime.datetime.now() - wraps the real datetime.datetime.now() .
  • escape_hatch.datetime.datetime.utcnow() - wraps the real datetime.datetime.utcnow() .
  • escape_hatch.time.clock_gettime() - wraps the real time.clock_gettime() .
  • escape_hatch.time.clock_gettime_ns() - wraps the real time.clock_gettime_ns() .
  • escape_hatch.time.gmtime() - wraps the real time.gmtime() .
  • escape_hatch.time.localtime() - wraps the real time.localtime() .
  • escape_hatch.time.strftime() - wraps the real time.strftime() .
  • escape_hatch.time.time() - wraps the real time.time() .
  • escape_hatch.time.time_ns() - wraps the real time.time_ns() .

Time is a global state. Any concurrent threads or asynchronous functions are also be affected. Some aren't ready for time to move so rapidly or backwards, and may crash or produce unexpected results.

Also beware that other processes are not affected. For example, if you use SQL datetime functions on a database server, they will return the real time.

There are some prior libraries that try to achieve the same thing. They have their own strengths and weaknesses. Here's a quick comparison.

unittest.mock

The standard library's unittest.mock can be used to target imports of datetime and time to change the returned value for current time. Unfortunately, this is fragile as it only affects the import location the mock targets. Therefore, if you have several modules in a call tree requesting the date/time, you need several mocks. This is a general problem with unittest.mock - see Why Your Mock Doesn't Work .

It's also impossible to mock certain references, such as function default arguments:

Although such references are rare, they are occasionally used to optimize highly repeated loops.

Steve Pulec's freezegun library is a popular solution. It provides a clear API which was much of the inspiration for time-machine.

The main drawback is its slow implementation. It essentially does a find-and-replace mock of all the places that the datetime and time modules have been imported. This gets around the problems with using unittest.mock, but it means the time it takes to do the mocking is proportional to the number of loaded modules. In large projects, this can take several seconds, an impractical overhead for an individual test.

It's also not a perfect search, since it searches only module-level imports. Such imports are definitely the most common way projects use date and time functions, but they're not the only way. freezegun won’t find functions that have been “hidden” inside arbitrary objects, such as class-level attributes.

It also can't affect C extensions that call the standard library functions, including (I believe) Cython-ized Python code.

python-libfaketime

Simon Weber's python-libfaketime wraps the libfaketime library. libfaketime replaces all the C-level system calls for the current time with its own wrappers. It's therefore a "perfect" mock for the current process, affecting every single point the current time might be fetched, and performs much faster than freezegun.

Unfortunately python-libfaketime comes with the limitations of LD_PRELOAD . This is a mechanism to replace system libraries for a program as it loads ( explanation ). This causes two issues in particular when you use python-libfaketime.

First, LD_PRELOAD is only available on Unix platforms, which prevents you from using it on Windows.

Second, you have to help manage LD_PRELOAD . You either use python-libfaketime's reexec_if_needed() function, which restarts ( re-execs ) your test process while loading, or manually manage the LD_PRELOAD environment variable. Neither is ideal. Re-execing breaks anything that might wrap your test process, such as profilers, debuggers, and IDE test runners. Manually managing the environment variable is a bit of overhead, and must be done for each environment you run your tests in, including each developer's machine.

time-machine is intended to combine the advantages of freezegun and libfaketime. It works without LD_PRELOAD but still mocks the standard library functions everywhere they may be referenced. Its weak point is that other libraries using date/time system calls won't be mocked. Thankfully this is rare. It's also possible such python libraries can be added to the set mocked by time-machine.

One drawback is that it only works with CPython, so can't be used with other Python interpreters like PyPy. However it may possible to extend it to support other interpreters through different mocking mechanisms.

Migrating from libfaketime or freezegun

freezegun has a useful API, and python-libfaketime copies some of it, with a different function name. time-machine also copies some of freezegun's API, in travel() 's destination , and tick arguments, and the shift() method. There are a few differences:

  • time-machine's tick argument defaults to True , because code tends to make the (reasonable) assumption that time progresses whilst running, and should normally be tested as such. Testing with time frozen can make it easy to write complete assertions, but it's quite artificial. Write assertions against time ranges, rather than against exact values.
  • freezegun interprets dates and naive datetimes in the local time zone (including those parsed from strings with dateutil ). This means tests can pass when run in one time zone and fail in another. time-machine instead interprets dates and naive datetimes in UTC so they are fixed points in time. Provide time zones where required.
  • freezegun's tick() method has been implemented as shift() , to avoid confusion with the tick argument. It also requires an explicit delta rather than defaulting to 1 second.
  • freezegun's tz_offset argument is not supported, since it only partially mocks the current time zone. Time zones are more complicated than a single offset from UTC, and freezegun only uses the offset in time.localtime() . Instead, time-machine will mock the current time zone if you give it a datetime with a ZoneInfo timezone.

Some features aren't supported like the auto_tick_seconds argument. These may be added in a future release.

If you are only fairly simple function calls, you should be able to migrate by replacing calls to freezegun.freeze_time() and libfaketime.fake_time() with time_machine.travel() .

time machine travel python

The maintainers of this project get paid by Tidelift to make sure it meets pre-defined standards around security, maintenance and licensing.

Want to learn more? Chat with an expert at Tidelift.

The Tidelift Subscription provides access to a continuously curated stream of human-researched and maintainer-verified data on open source packages and their licenses, releases, vulnerabilities, and development practices.

Adam Johnson

See all contributors

Something wrong with this page? Make a suggestion

Export .ABOUT file for this package

Last synced: 2024-03-22 23:15:00 UTC

Login to resync this project

  • Español – AmĂ©rica Latina
  • PortuguĂȘs – Brasil
  • Documentation

Data retention with time travel and fail-safe

This document describes time travel and fail-safe data retention for datasets. During the time travel and fail-safe periods, data that you have changed or deleted in any table in the dataset continues to be stored in case you need to recover it.

Time travel

You can access data from any point within the time travel window, which covers the past seven days by default. Time travel lets you query data that was updated or deleted, restore a table or dataset that was deleted, or restore a table that expired.

Configure the time travel window

You can set the duration of the time travel window, from a minimum of two days to a maximum of seven days. Seven days is the default. You set the time travel window at the dataset level, which then applies to all of the tables within the dataset.

You can configure the time travel window to be longer in cases where it is important to have a longer time to recover updated or deleted data, and to be shorter where it isn't required. Using a shorter time travel window lets you save on storage costs when using the physical storage billing model . These savings don't apply when using the logical storage billing model.

For more information on how the storage billing model affects cost, see Billing .

How the time travel window affects table and dataset recovery

A deleted table or dataset uses the time travel window duration that was in effect at the time of deletion.

For example, if you have a time travel window duration of two days and then increase the duration to seven days, tables deleted before that change are still only recoverable for two days. Similarly, if you have a time travel window duration of five days and you reduce that duration to three days, any tables that were deleted before the change are still recoverable for five days.

Because time travel windows are set at the dataset level, you can't change the time travel window of a deleted dataset until it is undeleted.

If you reduce the time travel window duration, delete a table, and then realize that you need a longer period of recoverability for that data, you can create a snapshot of the table from a point in time prior to the table deletion. You must do this while the deleted table is still recoverable. For more information, see Create a table snapshot using time travel .

Specify a time travel window

You can use the Google Cloud console, the bq command-line tool, or the BigQuery API to specify the time travel window for a dataset.

For instructions on how to specify the time travel window for a new dataset, see Create datasets .

For instructions on how to update the time travel window for an existing dataset, see Update time travel windows .

If the timestamp specifies a time outside time travel window, or from before the table was created, then the query fails and returns an error like the following:

Time travel and row-level access

If a table has, or has had, row-level access policies , then only a table administrator can access historical data for the table.

The following Identity and Access Management (IAM) permission is required:

The following BigQuery role provides the required permission:

The bigquery.rowAccessPolicies.overrideTimeTravelRestrictions permission can't be added to a custom role .

Run the following command to get the equivalent Unix epoch time:

Replace the UNIX time 1691164834000 received from the above command in the bq command-line tool. Run the following command to restore a copy of the deleted table deletedTableID in another table restoredTable , within the same dataset myDatasetID :

BigQuery provides a fail-safe period. During the fail-safe period, deleted data is automatically retained for an additional seven days after the time travel window, so that the data is available for emergency recovery. Data is recoverable at the table level. Data is recovered for a table from the point in time represented by the timestamp of when that table was deleted. The fail-safe period is not configurable.

You can't query or directly recover data in fail-safe storage. To recover data from fail-safe storage, contact Cloud Customer Care .

If you set your storage billing model to use physical bytes, the total storage costs you are billed for include the bytes used for time travel and fail-safe storage. If you set your storage billing model to use logical bytes, the total storage costs you are billed for do not include the bytes used for time travel or fail-safe storage. You can configure the time travel window to balance storage costs with your data retention needs.

If you use physical storage, you can see the bytes used by time travel and fail-safe by looking at the TIME_TRAVEL_PHYSICAL_BYTES and FAIL_SAFE_PHYSICAL_BYTES columns in the TABLE_STORAGE and TABLE_STORAGE_BY_ORGANIZATION views.

Limitations

  • Time travel only provides access to historical data for the duration of the time travel window. To preserve table data for non-emergency purposes for longer than the time travel window, use table snapshots .
  • If a table has, or has previously had, row-level access policies, then time travel can only be used by table administrators. For more information, see Time travel and row-level access .
  • Time travel does not restore table metadata.

What's next

  • Learn how to query and recover time travel data .
  • Learn more about table snapshots .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-04-29 UTC.

time machine travel python

Time Machines: From H.G. Wells to Modern Science

T he concept of time travel has always captured the human imagination, fueling dreams of voyages to the past or future, altering historical events, or witnessing distant futures. While often relegated to the realm of science fiction, the idea of time machines has evolved over the years, transitioning from the imaginative works of authors like H.G. Wells to the cutting-edge theories and scientific advancements of today. In this article, we’ll explore the fascinating journey of time machines, tracing their origins, exploring their fictional and scientific manifestations, and delving into the tantalizing possibilities they present for our understanding of time and reality.

Introduction to Time Machines

A time machine, as envisioned in science fiction and theoretical physics, is a hypothetical device or concept that enables an individual or object to travel through time, navigating the temporal landscape of past, present, and future, and exploring the mysteries of time dilation, causality, and the fabric of spacetime itself.

  • Cultural Impact and Imagination: Time machines have captivated the public’s imagination, inspiring countless stories, films, and discussions about the nature of time, destiny, and the possibilities of temporal exploration within the realms of fiction and reality.
  • Scientific Theories and Speculations: Time machines have been the subject of scientific research, theoretical debates, and mathematical explorations within the frameworks of general relativity, quantum mechanics, and the mysteries of the cosmos, offering insights into the potential pathways, paradoxes, and challenges of time travel within the fabric of reality and the universe.

H.G. Wells and the Time Machine: A Journey into the Past

H.G. Wells’ seminal work, “The Time Machine,” published in 1895, introduced the world to the concept of a machine capable of time travel, shaping the cultural perception, scientific speculations, and fictional explorations of time machines for generations to come.

  • Literary Legacy and Imaginative Exploration: Wells’ novel delves into the adventures of an inventor who creates a machine capable of traveling through time, exploring the future landscape of humanity, societal evolution, and the mysteries of time, destiny, and human civilization within the framework of science fiction and the human imagination.
  • Cultural Impact and Scientific Inspiration: “The Time Machine” has inspired generations of readers, writers, scientists, and thinkers, shaping the cultural perception of time machines, inspiring scientific research, and theoretical speculations about the nature of time, reality, and the possibilities of temporal exploration within the realms of fiction and scientific inquiry.

Scientific Theories, Quantum Mechanics, and Time Travel

In the realm of theoretical physics, time travel has been explored through the frameworks of general relativity, quantum mechanics, and the mysteries of the cosmos, offering insights into the potential pathways, paradoxes, and challenges of time travel within the fabric of reality and the universe.

  • General Relativity and Spacetime Geometry: Albert Einstein’s theory of general relativity describes gravity as the curvature of spacetime, offering mathematical equations, principles, and insights that explore the potential for time dilation, wormholes, black holes, and the mysterious cosmic phenomena that shape the fabric of reality and the universe.
  • Quantum Mechanics, Entanglement, and Quantum Time Dynamics: Quantum mechanics introduces the principles of superposition, entanglement, and the mysterious quantum phenomena that challenge our classical understanding of time, reality, and the nature of the cosmos, offering insights into the non-deterministic, probabilistic nature of quantum systems, time evolution, and the quantum correlations that transcend classical boundaries and the mysteries of the quantum realm.

Modern Science, Technological Innovations, and Time Travel

Advancements in science, technology, and theoretical research have sparked renewed interest, innovations, and possibilities for exploring the concept of time travel, temporal dynamics, and the mysteries of the universe within the context of modern science and technological advancements.

  • Time Dilation, Relativistic Effects, and Cosmic Observations: Observations of time dilation effects in high-speed particle accelerators, spacecraft, and cosmic phenomena provide empirical evidence, insights, and challenges for understanding the nature of time, spacetime geometry, and the cosmic dynamics that shape our understanding of time travel and the mysteries of the universe.
  • Black Holes, Wormholes, and Cosmic Gateways: Theoretical constructs, such as black holes, wormholes, and cosmic gateways, offer potential pathways, mathematical models, and speculative possibilities for time travel, time dilation, and the exploration of the temporal landscape within the framework of general relativity, quantum mechanics, and the mysteries of the cosmos.

Time machines, from H.G. Wells’ imaginative narrative to modern scientific theories and technological innovations, reflect humanity’s enduring fascination with time travel, the mysteries of the temporal landscape, and the timeless quest for understanding, enlightenment, and the boundless possibilities that lie within the fabric of reality and the cosmic tapestry.

As we explore, investigate, and unravel the captivating journey of time machines through historical inquiry, scientific exploration, and the pursuit of knowledge, we embark on a journey of discovery, exploration, and enlightenment that transcends boundaries, deepens our understanding of human creativity, imagination, and the enduring quest for truth, meaning, and the timeless wonders that inspire wonder, curiosity, and a renewed appreciation for the grandeur, diversity, and interconnectedness of the human experience, cultural heritage, and the boundless realms of time, space, and the universe beyond.

Read More: The Goldilocks Zone: Finding Planets Just Right for Life

Time Machines: From H.G. Wells to Modern Science 6

IMAGES

  1. Time travel in Python !!

    time machine travel python

  2. A Beginner’s Guide to the Python time Module

    time machine travel python

  3. Python time module

    time machine travel python

  4. STEPHEN HAWKING: How To Build A Time Machine

    time machine travel python

  5. Time Module

    time machine travel python

  6. Time Travel Through your Database History

    time machine travel python

VIDEO

  1. time machine travel 🧳#viral #you tube

  2. Back To The Future Crysis Mod

  3. Allen and George: The Time Machine

  4. Back to the Future

  5. The Science Behind Time Travel

  6. Time Travel Machine History Nikola Tesla Invention#Shorts#GeniusInventor

COMMENTS

  1. time-machine · PyPI

    travel (destination, *, tick=True) travel () is a class that allows time travel, to the datetime specified by destination . It does so by mocking all functions from Python's standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager.

  2. adamchainz/time-machine: Travel through time in your tests.

    If the destination passed to time_machine.travel() or Coordinates.move_to() has its tzinfo set to a zoneinfo.ZoneInfo instance_, the current timezone will be mocked. This will be done by calling time.tzset()_, so it is only available on Unix.The zoneinfo module is new in Python 3.8 - on older Python versions use the backports.zoneinfo package_, by the original zoneinfo author.

  3. How to Use Python to Time Travel: Exploring Datetime

    First Stop: Importing the Time Machine (Datetime) 🚀 Let's start by summoning the time machine. How? By importing the datetime module, of course! This module is like the flux capacitor of your DeLorean - it's what makes time travel possible. Just don't hit 88 miles per hour, or who knows where you'll end up!

  4. Introducing Delta Time Travel for Large Scale Data Lakes

    Python syntax: df = spark.read \ . format ("delta") \ .option ... Time travel also plays an important role in machine learning and data science. Reproducibility of models and experiments is a key consideration for data scientists, because they often create 100s of models before they put one into production, and in that time-consuming process ...

  5. Delorean · PyPI

    Delorean: Time Travel Made Easy. Delorean is a library for clearing up the inconvenient truths that arise dealing with datetimes in Python. Understanding that timing is a delicate enough of a problem delorean hopes to provide a cleaner less troublesome solution to shifting, manipulating, and generating datetimes.. Delorean stands on the shoulders of giants pytz and dateutil

  6. Introducing time-machine, a New Python Library for Mocking the Current

    The main drawback is its slow implementation. It essentially does a find-and-replace mock of all the places that the relevant functions from the datetime and time modules have been imported. This gets around the problems with using unittest.mock, but it means the time it takes to do the mocking is proportional to the number of loaded modules.In large projects, this can take a second or two, an ...

  7. time-travel's documentation

    time-travel's documentation ¶. time-travel's documentation. time-travel is a python library that allows users to write deterministic tests for time sensitive and I/O intensive code. time-travel supports python 2.7, 3.5, 3.6, 3.7 and pypy on both Linux and Windows. Quick start ¶.

  8. PyTrace

    1. Install tracing package via pip in your virtual environment: 2. Add attribute @trace to the method you want to record. some_code() Your recording will be stored in your working directory. 3. Open your recording in web app to analyze. PyTrace is a time travel recorder/analyzer for Python.

  9. Time Travel Made Easy: A Comprehensive Guide to Python Datetime

    The datetime module in Python's standard library provides classes that can work with dates, times, and time intervalsÂč. This module is particularly important in data analysis because dates and times are often key components of data, and manipulating them accurately is essential for projects such as time series analysis and financial modeling.

  10. Fire up your Python time machine (and test some code)

    Python Bytes podcast delivers headlines directly to your earbuds. News and announcements from the Python community for the week of Aug 4th, 2021 ... from datetime import datetime import time_machine @time_machine.travel("2021-01-01 21:00") def test_in_the_past(): assert datetime.now() == datetime(2021, 1, 1, 21, 0) ----- # The time_machine ...

  11. Exploring the Relativity of Time: Simulating Time Dilation with Python

    Here we notice that, if we travel at 99.99% the speed of light, for it to go 1000 years on earth, we would only have to travel 14.14 years, and the closer we get to c, the less time we would have ...

  12. Travel through time in your tests

    travel(destination, *, tick=True) travel() is a class that allows time travel, to the datetime specified by destination. It does so by mocking all functions from Python's standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager. destination specifies the datetime ...

  13. Mastering Space-Time Cubes with Python: A Practical Guide

    Implementing Space-Time Cubes in Python We will use the `geopandas` and `matplotlib` libraries for this illustration. Suppose we have a dataset of recorded earthquakes with their latitude ...

  14. travel-time-prediction · GitHub Topics · GitHub

    To associate your repository with the travel-time-prediction topic, visit your repo's landing page and select "manage topics." GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.

  15. time-machine 2.9.0 on PyPI

    travel(destination, *, tick=True) travel() is a class that allows time travel, to the datetime specified by destination . It does so by mocking all functions from Python's standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager. destination specifies the datetime ...

  16. How to calculate Travel time for any location in the world

    Isochrones (Travel time) First, we set up the points of interest and the graph network with the mode of transportation. Let us create a walk-by graph with 7k distance for Stockholm, a larger network. Once we create the walk-by Graph, the next step is to create nodes from the Graph (Snippet #2).

  17. Working with Timezones and Python using Pytz library

    One thing that you need to know is, as the main rule when working with timezone is that you will always work with the timezone UTC, in your database, in your code, and after to present you convert ...

  18. Data retention with time travel and fail-safe

    During the fail-safe period, deleted data is automatically retained for an additional seven days after the time travel window, so that the data is available for emergency recovery. Data is recoverable at the table level. Data is recovered for a table from the point in time represented by the timestamp of when that table was deleted.

  19. pandas

    1. Is there any way to calculate the minimum travel time from O-D route to point A, using Python and Google API or OSMnx library? O and D refer to the Origin and Destination points, respectively. For example: O is (30.2641922, -97.746646) D is (30.3034562, -97.7073463) and A is a "stop" point (30.2903708, -97.7264791) python. pandas.

  20. How to measure driving distance, time, and plot routes between ...

    To access the travel time and duration we can use the summary attribute. It returns the distance and duration between given points in meters and Minutes. First, we need to prepare the text for the ...

  21. Time Machines: From H.G. Wells to Modern Science

    H.G. Wells' seminal work, "The Time Machine," published in 1895, introduced the world to the concept of a machine capable of time travel, shaping the cultural perception, scientific ...