在Python中使用日期获取星期数 [英] Get week number using date in python

查看:312
本文介绍了在Python中使用日期获取星期数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日期是 datetime.date(2013,12,30)



我正在尝试获取周数使用

 导入datetime 
datetime.date(2013,12,30).isocalendar()[1]

我的输出为,

  1 

为什么我没有得到去年的星期数,而是我



我在这里做什么错了?

解决方案

您没有做错任何事,根据 2013/12/30 属于2014年的第1周。 wikipedia.org/wiki/ISO_week_date rel = noreferrer> ISO8601星期编号标准


ISO 8601定义第01周是该年的第一个星期四。


该周的星期四是2014/01/02。 p>

其他解释定义的方法,来自同一链接的Wiki Pedia文章:



  • 这是第一周,第一天的大部分时间(四天或以上) (ISO周从星期一开始)

  • 第一天是距离1月1日最近的星期一。

  • 其中有1月4日。因此,最早的日期是12月29日至1月4日,最晚的日期是1月4日至10月10日。

  • 如果周六,周日和1月1日不工作,则它具有今年的第一个工作日。


如果您要查找给定年份的最后一周(52或53) ,具体取决于年份),我会使用12月28日,因为这总是保证在最后一周(因为1月4日始终是明年的第一周的一部分):

  def lastweeknumber(year):
返回datetime.date(year,12,28).isocalendar()[1]


Date is datetime.date(2013, 12, 30)

I am trying to get week number using

import datetime
datetime.date(2013, 12, 30).isocalendar()[1]

I am getting output as ,

1

Why i am not getting week number of last year , instead i am getting week number of current year?

Whats wrong i am doing here ?

解决方案

You are doing nothing wrong, 2013/12/30 falls in week 1 of 2014, according to the ISO8601 week numbering standard:

The ISO 8601 definition for week 01 is the week with the year's first Thursday in it.

The Thursday in that week is 2014/01/02.

Other ways to explain the definition, from the same linked WikiPedia article:

  • It is the first week with a majority (four or more) of its days in January (ISO weeks start on Monday)
  • Its first day is the Monday nearest to 1 January.
  • It has 4 January in it. Hence the earliest possible dates are 29 December through 4 January, the latest 4 through 10 January.
  • It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.

If you were looking for the last week number of a given year (52 or 53, depending on the year), I'd use December 28th, which is always guaranteed to be in the last week (because January 4th is always part of the first week of the next year):

def lastweeknumber(year):
    return datetime.date(year, 12, 28).isocalendar()[1]

这篇关于在Python中使用日期获取星期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆