从python中的当前日期获取7天前的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20573459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:45:00 来源:igfitidea点击:
Getting the date of 7 days ago from current date in python
提问by John Adam
I'm trying to get the date that was 7 days ago starting from current date in python. Can anyone help me?
我正在尝试从 python 中的当前日期开始获取 7 天前的日期。谁能帮我?
回答by unutbu
import datetime as DT
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
回答by mgilson
>>> 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:
如果你真的只想要日期,你可以调用 date 方法:
>>> (datetime.datetime.now() - datetime.timedelta(days=7)).date()
datetime.date(2013, 12, 6)
Or, work with dates to begin with as suggested by unutbu.
或者,按照 unutbu 的建议使用开始日期。

