How to get all datetime instances of the current week, given a day?

狂风中的少年 提交于 2019-12-06 04:34:16

问题


Given a day, I want to get all days(datetime instances) of the week in which day is present.

I have a solution, please correct me if there is something wrong of if more efficient method exists.

>>> import datetime
>>> today = datetime.datetime(2013, 06, 26)
>>> today
datetime.datetime(2013, 6, 26, 0, 0)
>>> day_of_week = today.isocalendar()[2] - 1
>>> day_of_week
2
>>> start_date = today - timedelta(days=day_of_week)
>>> start_date
datetime.datetime(2013, 6, 24, 0, 0) # Got monday
>>> dates = [start + timedelta(days=i) for i in range(7)]
>>> dates
[datetime.datetime(2013, 6, 24, 0, 0),
 datetime.datetime(2013, 6, 25, 0, 0),
 datetime.datetime(2013, 6, 26, 0, 0),
 datetime.datetime(2013, 6, 27, 0, 0),
 datetime.datetime(2013, 6, 28, 0, 0),
 datetime.datetime(2013, 6, 29, 0, 0),
 datetime.datetime(2013, 6, 30, 0, 0)]

I want monday to be start date and sunday the end date.


回答1:


I'd use datetime.date() instead to make it clear we are calculating dates here, and use date.weekday() to get the current weekday instead of using the .isocalendar() call, giving us a 0-based weekday number (0 is Monday).

import datetime

today = datetime.date(2013, 06, 26)
dates = [today + datetime.timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())]

Demo:

>>> from pprint import pprint
>>> import datetime
>>> today = datetime.date(2013, 06, 26)
>>> pprint([today + datetime.timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())])
[datetime.date(2013, 6, 24),
 datetime.date(2013, 6, 25),
 datetime.date(2013, 6, 26),
 datetime.date(2013, 6, 27),
 datetime.date(2013, 6, 28),
 datetime.date(2013, 6, 29),
 datetime.date(2013, 6, 30)]

On python 2 you can replace range() with xrange() if you like; for a 7-day value that won't make much difference.

Just to make it explicit; datetime.weekday() exists as well, and there is a .isoweekday() too, so there is no need to use .isocalendar() anywhere.



来源:https://stackoverflow.com/questions/17277002/how-to-get-all-datetime-instances-of-the-current-week-given-a-day

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