How to go back days in datetime, python?

0

I need to return a string in the format "dd / mm / yyyy" in python, I got through the datetime library.

import datetime
date = datetime.datetime.now().strftime("%d/%m/%y")

But I also need the date 7 days ago, a week earlier.

    
asked by anonymous 02.01.2018 / 13:14

1 answer

4

You can do the following, datetime.timedelta :

import datetime

date_now = datetime.datetime.now()
seven_days_ago = date_now - datetime.timedelta(days=7)
print('now:', date_now.strftime("%d/%m/%y")) # 02/01/18
print('7 dias atrás:', seven_days_ago.strftime("%d/%m/%y")) # 26/12/17

DEMONSTRATION

    
02.01.2018 / 13:19