Python: How do I mock datetime.utcnow()?

后端 未结 5 1045
梦如初夏
梦如初夏 2020-12-30 02:24

I have the below:

from datetime import datetime

def get_report_month_key():
    month_for_report = datetime.utcnow()
    return month_for_report.strftime(\"         


        
5条回答
  •  难免孤独
    2020-12-30 02:43

    What also works when patching built-in Python modules turns out to be complicated (as it is with datetime, see e.g. https://solidgeargroup.com/mocking-the-time or https://nedbatchelder.com/blog/201209/mocking_datetimetoday.html or https://gist.github.com/rbarrois/5430921) is wrapping the function in a custom one which then can be easily patched.

    So, instead of calling datetime.datetime.utcnow(), you use a function like

    import datetime
    
    
    def get_utc_now():
        return datetime.datetime.utcnow()
    

    Then, patching this one is as simple as

    import datetime
    
    # use whatever datetime you need here    
    fixed_now = datetime.datetime(2017, 8, 21, 13, 42, 20)
    with patch('your_module_name.get_utc_now', return_value=fixed_now):
        # call the code using get_utc_now() here
        pass
    

    Using the patch decorator instead of the context manager would work similarly.

提交回复
热议问题