如何使用 Python 获取当前星期?

发布于 2024-08-16 15:54:32 字数 316 浏览 1 评论 0原文

使用Python...

我怎样才能获得特定一周中的天数列表?

就像......

{
'1' : ['01/03/2010','01/04/2010','01/05/2010','01/06/2010','01/07/2010','01/08/2010','01/09/2010'],  
'2' : ['01/10/2010','01/11/2010','01/12/2010','01/13/2010','01/14/2010','01/15/2010','01/16/2010'] 
}

这个例子中字典的键是周数。

Using Python...

How can I get a list of the days in a specific week?

Something like...

{
'1' : ['01/03/2010','01/04/2010','01/05/2010','01/06/2010','01/07/2010','01/08/2010','01/09/2010'],  
'2' : ['01/10/2010','01/11/2010','01/12/2010','01/13/2010','01/14/2010','01/15/2010','01/16/2010'] 
}

The key of the dictionary in this example would be the week number.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

も星光 2024-08-23 15:54:32

提防!如果您想定义自己的周数,可以使用提供的生成器表达式 在你的第一个问题中,顺便说一句,得到了一个很棒的答案)。如果您想遵循 ISO 周数惯例,则需要小心:

一年中的第一个日历周是
包括第一个的那个
那年的星期四和 [...]
日历年的最后一个日历周
是紧接之前的一周
下一个日历周
历年。

例如,2010 年 1 月 1 日和 2 日不是 2010 年的第一周,而是 2009 年的第 53 周。Python

提供了一个使用 ISO 日历查找周数的模块:

示例代码:

h[1] >>> import datetime
h[1] >>> Jan1st = datetime.date(2010,1,1)
h[1] >>> Year,WeekNum,DOW = Jan1st.isocalendar() # DOW = day of week
h[1] >>> print Year,WeekNum,DOW
2009 53 5

注意,再次说明 2010 年 1 月 1 日如何对应 2009 年第 53 周。

使用上一个答案中提供的生成器:

from datetime import date, timedelta


def allsundays(year):
    """This code was provided in the previous answer! It's not mine!"""
    d = date(year, 1, 1)                    # January 1st                                                          
    d += timedelta(days = 6 - d.weekday())  # First Sunday                                                         
    while d.year == year:
        yield d
        d += timedelta(days = 7)

Dict = {}
for wn,d in enumerate(allsundays(2010)):
    # This is my only contribution!
    Dict[wn+1] = [(d + timedelta(days=k)).isoformat() for k in range(0,7) ]

print Dict

Dict 包含您请求的字典。

Beware! If you want to define YOUR OWN week numbers, you could use the generator expression provided in your first question which, by the way, got an awesome answer). If you want to follow the ISO convention for week numbers, you need to be careful:

the first calendar week of a year is
that one which includes the first
Thursday of that year and [...] the
last calendar week of a calendar year
is the week immediately preceding the
first calendar week of the next
calendar year.

So, for instance, January 1st and 2nd in 2010 were NOT week one of 2010, but week 53 of 2009.

Python offers a module for finding the week number using the ISO calendar:

Example code:

h[1] >>> import datetime
h[1] >>> Jan1st = datetime.date(2010,1,1)
h[1] >>> Year,WeekNum,DOW = Jan1st.isocalendar() # DOW = day of week
h[1] >>> print Year,WeekNum,DOW
2009 53 5

Notice, again, how January 1st 2010 corresponds to week 53 of 2009.

Using the generator provided in the previous answer:

from datetime import date, timedelta


def allsundays(year):
    """This code was provided in the previous answer! It's not mine!"""
    d = date(year, 1, 1)                    # January 1st                                                          
    d += timedelta(days = 6 - d.weekday())  # First Sunday                                                         
    while d.year == year:
        yield d
        d += timedelta(days = 7)

Dict = {}
for wn,d in enumerate(allsundays(2010)):
    # This is my only contribution!
    Dict[wn+1] = [(d + timedelta(days=k)).isoformat() for k in range(0,7) ]

print Dict

Dict contains the dictionary you request.

相思故 2024-08-23 15:54:32

如何识别周数?在这里,我通过该周的某一天进行标识,使用一个函数获取该周的星期日(您在示例中使用的函数),然后返回它加上接下来的 6 天。

import datetime

one_day = datetime.timedelta(days=1)

def get_week(date):
  """Return the full week (Sunday first) of the week containing the given date.

  'date' may be a datetime or date instance (the same type is returned).
  """
  day_idx = (date.weekday() + 1) % 7  # turn sunday into 0, monday into 1, etc.
  sunday = date - datetime.timedelta(days=day_idx)
  date = sunday
  for n in xrange(7):
    yield date
    date += one_day

print list(get_week(datetime.datetime.now().date()))
# [datetime.date(2010, 1, 3), datetime.date(2010, 1, 4),
#  datetime.date(2010, 1, 5), datetime.date(2010, 1, 6),
#  datetime.date(2010, 1, 7), datetime.date(2010, 1, 8),
#  datetime.date(2010, 1, 9)]
print [d.isoformat() for d in get_week(datetime.datetime.now().date())]
# ['2010-01-03', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07',
#  '2010-01-08', '2010-01-09']

How do you identify weeks? Here I'm identifying by a day in that week, using a function which gets the Sunday in that week (what you used in your example), and then returns it plus the next 6 days.

import datetime

one_day = datetime.timedelta(days=1)

def get_week(date):
  """Return the full week (Sunday first) of the week containing the given date.

  'date' may be a datetime or date instance (the same type is returned).
  """
  day_idx = (date.weekday() + 1) % 7  # turn sunday into 0, monday into 1, etc.
  sunday = date - datetime.timedelta(days=day_idx)
  date = sunday
  for n in xrange(7):
    yield date
    date += one_day

print list(get_week(datetime.datetime.now().date()))
# [datetime.date(2010, 1, 3), datetime.date(2010, 1, 4),
#  datetime.date(2010, 1, 5), datetime.date(2010, 1, 6),
#  datetime.date(2010, 1, 7), datetime.date(2010, 1, 8),
#  datetime.date(2010, 1, 9)]
print [d.isoformat() for d in get_week(datetime.datetime.now().date())]
# ['2010-01-03', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07',
#  '2010-01-08', '2010-01-09']
反差帅 2024-08-23 15:54:32
current_week = datetime.datetime.now().isocalendar()[1]
current_week = datetime.datetime.now().isocalendar()[1]
过去的过去 2024-08-23 15:54:32

在阅读该问题后,我开发了一个 3 行方法:

from datetime import timedelta

def get_week_dates(base_date, start_day, end_day=None):
    """
    Return entire week of dates based on given date limited by start_day and end_day.
    If end_day is None, return only start_day.

    >>> from datetime import date
    >>> get_week_dates(date(2015,1,16), 3, 5)
    [datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]

    >>> get_week_dates(date(2015,1,15), 2, 5)
    [datetime.date(2015, 1, 13), datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]
    """
    monday = base_date - timedelta(days=base_date.isoweekday() - 1)
    week_dates = [monday + timedelta(days=i) for i in range(7)]
    return week_dates[start_day - 1:end_day or start_day]

使用 get_week_dates(date.today(), 1, 7) 获取当前星期的日期。

There is a 3 lines method I developed after read that question:

from datetime import timedelta

def get_week_dates(base_date, start_day, end_day=None):
    """
    Return entire week of dates based on given date limited by start_day and end_day.
    If end_day is None, return only start_day.

    >>> from datetime import date
    >>> get_week_dates(date(2015,1,16), 3, 5)
    [datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]

    >>> get_week_dates(date(2015,1,15), 2, 5)
    [datetime.date(2015, 1, 13), datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]
    """
    monday = base_date - timedelta(days=base_date.isoweekday() - 1)
    week_dates = [monday + timedelta(days=i) for i in range(7)]
    return week_dates[start_day - 1:end_day or start_day]

Use get_week_dates(date.today(), 1, 7) to get current week dates.

千年*琉璃梦 2024-08-23 15:54:32

您可以使用日期时间模块。您可以指定格式和一切。这是链接:http://docs.python.org/library/datetime.html

查看 datetime.datetime( params ) 和 datetime.timedelta( params )。希望一切顺利;-)

示例:

import datetime

numweeks = 5
start_date = datetime.datetime(year=2010,month=1,day=4)    

weeks = {}

offset = datetime.timedelta(days=0)
for week in range(numweeks):
   this_week = []
   for day in range(7):
        date = start_date + offset
        date = date.strftime( some_format_string )
        this_week.append( date )
        offset += datetime.timedelta(days=1)
   weeks[week] = this_week 

You could use the datetime module. You can specify the format and everything. Here's the link: http://docs.python.org/library/datetime.html

Look into datetime.datetime( params ) and datetime.timedelta( params ). Hope it all goes well ;-)

Example:

import datetime

numweeks = 5
start_date = datetime.datetime(year=2010,month=1,day=4)    

weeks = {}

offset = datetime.timedelta(days=0)
for week in range(numweeks):
   this_week = []
   for day in range(7):
        date = start_date + offset
        date = date.strftime( some_format_string )
        this_week.append( date )
        offset += datetime.timedelta(days=1)
   weeks[week] = this_week 
罪#恶を代价 2024-08-23 15:54:32

这是一些代码:

import datetime

now = datetime.datetime.now()

now_day_1 = now - datetime.timedelta(days=now.weekday())

dates = {}

for n_week in range(3):
    dates[n_week] = [(now_day_1 + datetime.timedelta(days=d+n_week*7)).strftime("%m/%d/%Y") for d in range(7)]

print dates

打印:

{
 0: ['01/04/2010', '01/05/2010', '01/06/2010', '01/07/2010', '01/08/2010', '01/09/2010', '01/10/2010'], 
 1: ['01/11/2010', '01/12/2010', '01/13/2010', '01/14/2010', '01/15/2010', '01/16/2010', '01/17/2010'], 
 2: ['01/18/2010', '01/19/2010', '01/20/2010', '01/21/2010', '01/22/2010', '01/23/2010', '01/24/2010']
}

Here's some code:

import datetime

now = datetime.datetime.now()

now_day_1 = now - datetime.timedelta(days=now.weekday())

dates = {}

for n_week in range(3):
    dates[n_week] = [(now_day_1 + datetime.timedelta(days=d+n_week*7)).strftime("%m/%d/%Y") for d in range(7)]

print dates

prints:

{
 0: ['01/04/2010', '01/05/2010', '01/06/2010', '01/07/2010', '01/08/2010', '01/09/2010', '01/10/2010'], 
 1: ['01/11/2010', '01/12/2010', '01/13/2010', '01/14/2010', '01/15/2010', '01/16/2010', '01/17/2010'], 
 2: ['01/18/2010', '01/19/2010', '01/20/2010', '01/21/2010', '01/22/2010', '01/23/2010', '01/24/2010']
}
十六岁半 2024-08-23 15:54:32

如果您同意 ISO 标准:

>>> import collections
>>> dd = collections.defaultdict(list)
>>> jan1 = datetime.date(2010, 1, 1)
>>> oneday = datetime.timedelta(days=1)
>>> allyear = [jan1 + k*oneday for k in range(365 + 6)]
>>> for d in allyear:
...   y, w, wd = d.isocalendar()
...   if y == 2010: dd[w].append(d.strftime('%m/%d/%Y'))
... 

这会产生与您正在寻找的结果略有不同的结果(根据 ISO 标准,周从星期一开始,而不是星期日......),例如:

>>> dd[1]
['01/04/2010', '01/05/2010', '01/06/2010', '01/07/01/2010', '01/08/2010', '01/09/2010', '01/10/2010']

但您可以通过模拟来调整它适当的“关闭一”错误!-)

日历 模块允许您设置任何工作日作为“一周的第一天”,但没有提供获取所有周的简单方法(当一周分为两个月时不会重复),所以我认为直接工作 datetime 可能是一个更好的主意。

If you're OK with the ISO standard:

>>> import collections
>>> dd = collections.defaultdict(list)
>>> jan1 = datetime.date(2010, 1, 1)
>>> oneday = datetime.timedelta(days=1)
>>> allyear = [jan1 + k*oneday for k in range(365 + 6)]
>>> for d in allyear:
...   y, w, wd = d.isocalendar()
...   if y == 2010: dd[w].append(d.strftime('%m/%d/%Y'))
... 

This produces slightly different results than the ones you're looking for (by ISO standard, weeks begin on Monday, not Sunday...), e.g.:

>>> dd[1]
['01/04/2010', '01/05/2010', '01/06/2010', '01/07/01/2010', '01/08/2010', '01/09/2010', '01/10/2010']

but you could tweak this by simulating an appropriate "off by one" error!-)

The calendar modules let you set any weekday as "first day of week", but offers no simple way to get all weeks (without duplications when a week is split between two months), so I think that working directly off datetime is probably a better idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文