How to go back days on datetime, python?

Asked

Viewed 2,368 times

0

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

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

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

1 answer

4


Here’s what you can do, 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

  • 1

    Vlw was a great help.

  • You’re welcome @Viniciusmorais, good year

Browser other questions tagged

You are not signed in. Login or sign up in order to post.