Getting the date of 7 days ago from current date in python

PythonDatetime

Python Problem Overview


I'm trying to get the date that was 7 days ago starting from current date in python. Can anyone help me?

Python Solutions


Solution 1 - Python

import datetime as DT
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)

Solution 2 - Python

>>> import datetime
>>> datetime.datetime.now() - datetime.timedelta(days=7)
datetime.datetime(2013, 12, 6, 10, 29, 37, 596779)

If you really just want the date, you can call the date method:

>>> (datetime.datetime.now() - datetime.timedelta(days=7)).date()
datetime.date(2013, 12, 6)

Or, work with dates to begin with as suggested by unutbu.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn AdamView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonmgilsonView Answer on Stackoverflow