Search code examples
pythondatetimetimedelta

Apply a datetime to a file but for 1 day in the past


Does anyone know how I can apply a date one day in the past as my filename? With this code, it would give me a file name of 'File09202021161235.csv' however I would like this to output 1 day in the past.

 'File' + datetime.datetime.today().strftime('%m%d%Y%H%M%S''.csv')

I tired using timedelta(days=1) but then the strftime breaks? Can anyone offer any guidance?


Solution

  • It's very simple. First of all you are doing it wrong.

    datetime.timedelta(days=1)
    

    It's only the time for 1 days. It's not a current time. It's an interval.

    The fix is you need to subtract the this 1 days time interval from current time.

    import datetime
    
    #Here we are subtracting the current time with 1 days time interval
    past_day = datetime.datetime.today() - datetime.timedelta(days=1)
    your_file_name = 'File' + past_day.strftime('%m%d%Y%H%M%S''.csv')