How to find out what week number is current year on June 16th (wk24) with Python?
如何找出在6月16日(wk24)和Python之间的星期数是多少?
13 个解决方案
#1
265
datetime.date
has a isocalendar()
method, which returns a tuple containing the calendar week:
datetime。日期有一个isocalendar()方法,它返回一个包含日历周的元组:
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24
datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.
isocalendar()是一个实例方法,在给定的日期实例的相应顺序中返回包含年份、weeknumber和weekday的元组。
#2
62
I believe date.isocalendar()
is going to be the answer. This article explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the datetime page of the Python documentation.
我相信日期。isocalendar()将会是答案。这篇文章解释了ISO 8601日历背后的数学原理。查看Python文档的datetime页面中的date.isocalendar()部分。
>>> dt = datetime.date(2010, 6, 16)
>>> wk = dt.isocalendar()[1]
24
.isocalendar() return a 3-tuple with (year, wk num, wk day). dt.isocalendar()[0]
returns the year,dt.isocalendar()[1]
returns the week number, dt.isocalendar()[2]
returns the week day. Simple as can be.
.isocalendar()返回一个3元组(year, wk num, wk day)。dt.isocalendar()[0]返回年份,dt.isocalendar()[1]返回一周号,[2]返回工作日。简单的可以。
#3
49
You can get the week number directly from datetime as string.
您可以直接从datetime获得一个星期编号作为字符串。
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get diferent "types" of the week number of the year changing the strftime parameter for:
此外,您还可以获得年度的“类型”,以改变strftime参数:
%U - week number of the current year, starting with the first Sunday as the first day of the first week.
%U -周数,从第一个星期日开始,到第一周的第一天。
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.
%V -本年度的ISO 8601周数(01至53),其中第1周为本年度至少4天的第一周,周一为一周的第一天。
%W - week number of the current year, starting with the first Monday as the first day of the first week.
本年度的周数,以第一个星期一作为第一周的第一天开始。
I've got it from here. It worked for me in Python 2.7.6
我从这里得到的。它在Python 2.7.6中为我工作。
#4
26
Here's another option:
这是另一个选择:
import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))
which prints 24
.
打印24。
See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
见:http://docs.python.org/library/datetime.html strftime-and-strptime-behavior
#5
15
Generally to get the current week number (starts from Sunday):
一般来说,获得当前周数(从周日开始):
from datetime import *
today = datetime.today()
print today.strftime("%U")
#6
13
The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year.
别人建议的ISO周是很好的,但是它可能不适合你的需要。它假定每个星期从星期一开始,这将导致一些有趣的异常在年初和年底。
If you'd rather use a definition that says week 1 is always January 1 through January 7, regardless of the day of the week, use a derivation like this:
如果你更愿意使用一种定义,即1月1日一直是1月1日到1月7日,不管一周的哪一天,使用这样的推导:
>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24
#7
12
For the integer value of the instantaneous week of the year try:
对于年度的瞬时值的整数值,请尝试:
import datetime
datetime.datetime.utcnow().isocalendar()[1]
#8
8
If you are only using the isocalendar week number across the board the following should be sufficient:
如果你只使用isocalendar一周的数字,那么下面就应该足够了:
import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]
This retrieves the second member of the tuple returned by isocalendar for our week number.
这将检索isocalendar为我们的周号返回的tuple的第二个成员。
However, if you are going to be using date functions that deal in the Gregorian calendar, isocalendar alone will not work! Take the following example:
但是,如果您要使用在公历中处理的日期函数,那么isocalendar将无法工作!下面的例子:
import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]
The string here says to return the Monday of the first week in 2014 as our date. When we use isocalendar to retrieve the week number here, we would expect to get the same week number back, but we don't. Instead we get a week number of 2. Why?
这里的字符串表示将在2014年的第一个星期作为我们的日期返回。当我们使用isocalendar来检索这个星期的数字时,我们希望得到相同的星期号,但是我们没有。相反,我们得到了一个星期2的数字。为什么?
Week 1 in the Gregorian calendar is the first week containing a Monday. Week 1 in the isocalendar is the first week containing a Thursday. The partial week at the beginning of 2014 contains a Thursday, so this is week 1 by the isocalendar, and making date
week 2.
在公历的第一周是第一个星期包含一个星期一。在isocalendar的第一周是包含周四的第一周。2014年初的部分周包含一个周四,所以这是isocalendar的第一周,然后是第2周。
If we want to get the Gregorian week, we will need to convert from the isocalendar to the Gregorian. Here is a simple function that does the trick.
如果我们想要得到格里高利周,我们需要从isocalendar转换到格里高里。这里有一个简单的函数。
import datetime
def gregorian_week(date):
# The isocalendar week for this date
iso_week = date.isocalendar()[1]
# The baseline Gregorian date for the beginning of our date's year
base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")
# If the isocalendar week for this date is not 1, we need to
# decrement the iso_week by 1 to get the Gregorian week number
return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1
#9
6
You can try %W directive as below:
您可以尝试以下的%W指令:
d = datetime.datetime.strptime('2016-06-16','%Y-%m-%d')
print(datetime.datetime.strftime(d,'%W'))
'%W': Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. (00, 01, ..., 53)
“%W”:周数(星期一作为一周的第一天)作为一个十进制数。在第一个星期一之前的新年里,所有的日子都被认为是在第0周。(00,01,…53)
#11
2
isocalendar() returns incorrect year and weeknumber values for some dates:
isocalendar()在某些日期返回不正确的年份和weeknumber值:
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1
Compare with Mark Ransom's approach:
与马克·兰塞姆的方法相比:
>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52
#12
2
I summarize the discussion to two steps:
我将讨论总结为两个步骤:
- Convert the raw format to a
datetime
object. - 将原始格式转换为datetime对象。
- Use the function of a
datetime
object or adate
object to calculate the week number. - 使用datetime对象或日期对象的函数来计算周数。
Warm up
热身
```python
”“python
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
```
' ' '
1st step
第一步
To manually generate a datetime
object, we can use datetime.datetime(2017,5,3)
or datetime.datetime.now()
.
为了手动生成datetime对象,我们可以使用datetime.datetime(2017、5、3)或datetime.datetime.now()。
But in reality, we usually need to parse an existing string. we can use strptime
function, such as datetime.strptime('2017-5-3','%Y-%m-%d')
in which you have to specific the format. Detail of different format code can be found in the official documentation.
但实际上,我们通常需要解析现有的字符串。我们可以使用strptime函数,例如datetime.strptime('2017-5-3','%Y-%m-%d'),其中必须指定格式。不同格式代码的细节可以在官方文档中找到。
Alternatively, a more convenient way is to use dateparse module. Examples are dateparser.parse('16 Jun 2010')
, dateparser.parse('12/2/12')
or dateparser.parse('2017-5-3')
或者,更方便的方法是使用dateparse模块。例子是dateparser。parse('16 Jun 2010'), dateparser.parse('12/2/12')或dateparser.parse('2017-5-3')
The above two approaches will return a datetime
object.
以上两种方法将返回一个datetime对象。
2nd step
第二步
Use the obtained datetime
object to call strptime(format)
. For example,
使用获得的datetime对象调用strptime(格式)。例如,
```python
”“python
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.
```
' ' '
It's very tricky to decide which format to use. A better way is to get a date
object to call isocalendar()
. For example,
决定使用哪种格式非常困难。一个更好的方法是获取一个date对象调用isocalendar()。例如,
```python
”“python
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar()
print(year, week, weekday) # (2016,52,7) in the ISO standard
```
' ' '
In reality, you will be more likely to use date.isocalendar()
to prepare a weekly report, especially in the "Christmas-New Year" shopping season.
在现实中,你更有可能使用date.isocalendar()来准备每周的报告,特别是在“圣诞节-新年”购物季。
#13
0
userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ")
import datetime
currentDate = datetime.datetime.today()
testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date()
remainDays = testVar - currentDate.date()
remainWeeks = (remainDays.days / 7.0) + 1
print ("Please pay attention for deadline of project X in days and weeks are : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo hurryup.............!!!")
#1
265
datetime.date
has a isocalendar()
method, which returns a tuple containing the calendar week:
datetime。日期有一个isocalendar()方法,它返回一个包含日历周的元组:
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24
datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.
isocalendar()是一个实例方法,在给定的日期实例的相应顺序中返回包含年份、weeknumber和weekday的元组。
#2
62
I believe date.isocalendar()
is going to be the answer. This article explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the datetime page of the Python documentation.
我相信日期。isocalendar()将会是答案。这篇文章解释了ISO 8601日历背后的数学原理。查看Python文档的datetime页面中的date.isocalendar()部分。
>>> dt = datetime.date(2010, 6, 16)
>>> wk = dt.isocalendar()[1]
24
.isocalendar() return a 3-tuple with (year, wk num, wk day). dt.isocalendar()[0]
returns the year,dt.isocalendar()[1]
returns the week number, dt.isocalendar()[2]
returns the week day. Simple as can be.
.isocalendar()返回一个3元组(year, wk num, wk day)。dt.isocalendar()[0]返回年份,dt.isocalendar()[1]返回一周号,[2]返回工作日。简单的可以。
#3
49
You can get the week number directly from datetime as string.
您可以直接从datetime获得一个星期编号作为字符串。
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get diferent "types" of the week number of the year changing the strftime parameter for:
此外,您还可以获得年度的“类型”,以改变strftime参数:
%U - week number of the current year, starting with the first Sunday as the first day of the first week.
%U -周数,从第一个星期日开始,到第一周的第一天。
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.
%V -本年度的ISO 8601周数(01至53),其中第1周为本年度至少4天的第一周,周一为一周的第一天。
%W - week number of the current year, starting with the first Monday as the first day of the first week.
本年度的周数,以第一个星期一作为第一周的第一天开始。
I've got it from here. It worked for me in Python 2.7.6
我从这里得到的。它在Python 2.7.6中为我工作。
#4
26
Here's another option:
这是另一个选择:
import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))
which prints 24
.
打印24。
See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
见:http://docs.python.org/library/datetime.html strftime-and-strptime-behavior
#5
15
Generally to get the current week number (starts from Sunday):
一般来说,获得当前周数(从周日开始):
from datetime import *
today = datetime.today()
print today.strftime("%U")
#6
13
The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year.
别人建议的ISO周是很好的,但是它可能不适合你的需要。它假定每个星期从星期一开始,这将导致一些有趣的异常在年初和年底。
If you'd rather use a definition that says week 1 is always January 1 through January 7, regardless of the day of the week, use a derivation like this:
如果你更愿意使用一种定义,即1月1日一直是1月1日到1月7日,不管一周的哪一天,使用这样的推导:
>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24
#7
12
For the integer value of the instantaneous week of the year try:
对于年度的瞬时值的整数值,请尝试:
import datetime
datetime.datetime.utcnow().isocalendar()[1]
#8
8
If you are only using the isocalendar week number across the board the following should be sufficient:
如果你只使用isocalendar一周的数字,那么下面就应该足够了:
import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]
This retrieves the second member of the tuple returned by isocalendar for our week number.
这将检索isocalendar为我们的周号返回的tuple的第二个成员。
However, if you are going to be using date functions that deal in the Gregorian calendar, isocalendar alone will not work! Take the following example:
但是,如果您要使用在公历中处理的日期函数,那么isocalendar将无法工作!下面的例子:
import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]
The string here says to return the Monday of the first week in 2014 as our date. When we use isocalendar to retrieve the week number here, we would expect to get the same week number back, but we don't. Instead we get a week number of 2. Why?
这里的字符串表示将在2014年的第一个星期作为我们的日期返回。当我们使用isocalendar来检索这个星期的数字时,我们希望得到相同的星期号,但是我们没有。相反,我们得到了一个星期2的数字。为什么?
Week 1 in the Gregorian calendar is the first week containing a Monday. Week 1 in the isocalendar is the first week containing a Thursday. The partial week at the beginning of 2014 contains a Thursday, so this is week 1 by the isocalendar, and making date
week 2.
在公历的第一周是第一个星期包含一个星期一。在isocalendar的第一周是包含周四的第一周。2014年初的部分周包含一个周四,所以这是isocalendar的第一周,然后是第2周。
If we want to get the Gregorian week, we will need to convert from the isocalendar to the Gregorian. Here is a simple function that does the trick.
如果我们想要得到格里高利周,我们需要从isocalendar转换到格里高里。这里有一个简单的函数。
import datetime
def gregorian_week(date):
# The isocalendar week for this date
iso_week = date.isocalendar()[1]
# The baseline Gregorian date for the beginning of our date's year
base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")
# If the isocalendar week for this date is not 1, we need to
# decrement the iso_week by 1 to get the Gregorian week number
return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1
#9
6
You can try %W directive as below:
您可以尝试以下的%W指令:
d = datetime.datetime.strptime('2016-06-16','%Y-%m-%d')
print(datetime.datetime.strftime(d,'%W'))
'%W': Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. (00, 01, ..., 53)
“%W”:周数(星期一作为一周的第一天)作为一个十进制数。在第一个星期一之前的新年里,所有的日子都被认为是在第0周。(00,01,…53)
#10
#11
2
isocalendar() returns incorrect year and weeknumber values for some dates:
isocalendar()在某些日期返回不正确的年份和weeknumber值:
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1
Compare with Mark Ransom's approach:
与马克·兰塞姆的方法相比:
>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52
#12
2
I summarize the discussion to two steps:
我将讨论总结为两个步骤:
- Convert the raw format to a
datetime
object. - 将原始格式转换为datetime对象。
- Use the function of a
datetime
object or adate
object to calculate the week number. - 使用datetime对象或日期对象的函数来计算周数。
Warm up
热身
```python
”“python
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
```
' ' '
1st step
第一步
To manually generate a datetime
object, we can use datetime.datetime(2017,5,3)
or datetime.datetime.now()
.
为了手动生成datetime对象,我们可以使用datetime.datetime(2017、5、3)或datetime.datetime.now()。
But in reality, we usually need to parse an existing string. we can use strptime
function, such as datetime.strptime('2017-5-3','%Y-%m-%d')
in which you have to specific the format. Detail of different format code can be found in the official documentation.
但实际上,我们通常需要解析现有的字符串。我们可以使用strptime函数,例如datetime.strptime('2017-5-3','%Y-%m-%d'),其中必须指定格式。不同格式代码的细节可以在官方文档中找到。
Alternatively, a more convenient way is to use dateparse module. Examples are dateparser.parse('16 Jun 2010')
, dateparser.parse('12/2/12')
or dateparser.parse('2017-5-3')
或者,更方便的方法是使用dateparse模块。例子是dateparser。parse('16 Jun 2010'), dateparser.parse('12/2/12')或dateparser.parse('2017-5-3')
The above two approaches will return a datetime
object.
以上两种方法将返回一个datetime对象。
2nd step
第二步
Use the obtained datetime
object to call strptime(format)
. For example,
使用获得的datetime对象调用strptime(格式)。例如,
```python
”“python
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.
```
' ' '
It's very tricky to decide which format to use. A better way is to get a date
object to call isocalendar()
. For example,
决定使用哪种格式非常困难。一个更好的方法是获取一个date对象调用isocalendar()。例如,
```python
”“python
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar()
print(year, week, weekday) # (2016,52,7) in the ISO standard
```
' ' '
In reality, you will be more likely to use date.isocalendar()
to prepare a weekly report, especially in the "Christmas-New Year" shopping season.
在现实中,你更有可能使用date.isocalendar()来准备每周的报告,特别是在“圣诞节-新年”购物季。
#13
0
userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ")
import datetime
currentDate = datetime.datetime.today()
testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date()
remainDays = testVar - currentDate.date()
remainWeeks = (remainDays.days / 7.0) + 1
print ("Please pay attention for deadline of project X in days and weeks are : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo hurryup.............!!!")