Random Time-Freezing Function with Freezegun

  • Share this:

Code introduction


This custom function uses the Freezegun library to simulate a random time point and execute code within that frozen time.


Technology Stack : Freezegun

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import random
from freezegun import freeze_time

def random_freeze_time_function():
    def generate_random_time():
        from datetime import timedelta
        days = random.randint(0, 365)
        return (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')

    with freeze_time(generate_random_time()):
        return "This is a frozen time example."                
              
Tags: