如何基于python中的星期数获取星期的所有日期

时间:2019-05-16 07:25:29

标签: python python-2.7 datetime

我希望根据周号获取当前一周的所有日期。

我可以获得类似的周号

import datetime
weeknum=datetime.datetime.now().isocalendar()[1]

结果是20。

需要第20周的所有日期。 最终输出应该是

dates=['2019-05-12','2019-05-13','2019-05-14','2019-05-15','2019-05-16','2019-05-17','2019-05-18']

请帮助我。

6 个答案:

答案 0 :(得分:1)

使用timedelta和列表理解。

import datetime
theday = datetime.date.today()
weekday = theday.isoweekday()
# The start of the week
start = theday - datetime.timedelta(days=weekday)
# build a simple range
dates = [start + datetime.timedelta(days=d) for d in range(7)]

获取字符串输出

dates = [str(d) for d in dates]

答案 1 :(得分:1)

您可以使用timedatetime以及this答案建议来做到这一点,但可以根据您的要求进行更改:

WEEK  = 20 - 2 # as it starts with 0 and you want week to start from sunday
startdate = time.asctime(time.strptime('2019 %d 0' % WEEK, '%Y %W %w')) 
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y') 
dates = [startdate.strftime('%Y-%m-%d')] 
for i in range(1, 7): 
    day = startdate + datetime.timedelta(days=i)
    dates.append(day.strftime('%Y-%m-%d')) 

输出如下:

dates = ['2019-05-12',
         '2019-05-13',
         '2019-05-14',
         '2019-05-15',
         '2019-05-16',
         '2019-05-17',
         '2019-05-18']

答案 2 :(得分:1)

import datetime

# Starts with knowing the day of the week
week_day=datetime.datetime.now().isocalendar()[2]

# Calculates Starting date (Sunday) for this case by subtracting current date with time delta of the day of the week
start_date=datetime.datetime.now() - datetime.timedelta(days=week_day)

# Prints the list of dates in a current week
dates=[str((start_date + datetime.timedelta(days=i)).date()) for i in range(7)]
dates

输出为:

>>> dates
['2019-05-12', '2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16', '2019-05-17', '2019-05-18']

希望这可以为您提供帮助。祝你今天愉快。 :D

答案 3 :(得分:0)

我将研究以下两个问题。第一个应该帮助您计算给定星期数的开始日期-别忘了指定您的年份。

Get date from week number

然后,我将使用以下答案,而不是使用开始/结束日期,而是使用上方的开始日期并加上1天; 6次并将每个新日期存储在数组中。

Python: give start and end of week data from a given date

答案 4 :(得分:0)

您可以做的是-

weekdates = []
week_number = datetime.datetime.now().isocalendar()[1]
for day in range(7):
    week_date = datetime.datetime.strptime("2019-W{}".format(week_number)+ '-{}'.format(day), "%Y-W%W-%w")
    weekdates.append(week_date)

这是什么,它利用日期格式转换来根据星期几构造日期。

希望这会有所帮助。

答案 5 :(得分:0)

对于那些需要从星期一开始输出日期的人,可以这样调整:

import time
import datetime

WEEK  = 20 - 1 # as it starts with 0 and you want week to start from sunday
startdate = time.asctime(time.strptime('2019 %d 1' % WEEK, '%Y %W %w')) 
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y') 
dates = [startdate.strftime('%Y-%m-%d')] 
for i in range(1, 7): 
    day = startdate + datetime.timedelta(days=i)
    dates.append(day.strftime('%Y-%m-%d'))
print(dates)