get lastweek dates using python?

余生颓废 提交于 2019-12-07 06:20:00

问题


I am trying to get the date of the last week with python.

if date is : 10 OCT 2014 means

It should be print

10 OCT 2014, 09 OCT 2014, 08 OCT 2014, 07 OCT 2014, 06 OCT 2014, 05 OCT 2014, 04 OCT 2014

I tried:

today = (10 OCT 2014)

dates = [today + datetime.timedelta(days=i) for i in range(-4 - today.weekday(), 4 - today.weekday())]
print dates

I am getting this error:

exceptions.AttributeError: 'unicode' object has no attribute 'weekday'

回答1:


Your question and algorithm don't seem to correspond. Is this what you're after?

from datetime import date
from datetime import timedelta
today = date(2014, 10, 10) # or you can do today = date.today() for today's date

for i in range(0,7):
    print (today - timedelta(days=i))



回答2:


@MarkG hit the nail on the head but if you're looking to get the exact output as asked this would work:

import datetime

today = '10 OCT 2014'

dates = [datetime.datetime.strptime(today, '%d %b %Y') - datetime.timedelta(days=i) for i in range(7)]
print ', '.join([day.strftime('%d %b %Y').upper() for day in dates])

Note that you need to pass the today's date as a string.



来源:https://stackoverflow.com/questions/28478553/get-lastweek-dates-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!