Get date from week number

喜夏-厌秋 提交于 2019-11-26 03:28:59

问题


Please what\'s wrong with my code:

import datetime
d = \"2013-W26\"
r = datetime.datetime.strptime(d, \"%Y-W%W\")
print(r)

Display \"2013-01-01 00:00:00\", Thanks.


回答1:


A week number is not enough to generate a date; you need a day of the week as well. Add a default:

import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)

The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:

2013-07-01 00:00:00

%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.

See the strftime() and strptime() behaviour section in the documentation, footnote 4:

When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.

Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.




回答2:


To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):

import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)

%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:

2013-06-24 00:00:00

Availabe in Python 3.6+; from docs.




回答3:


import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res

Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.

datetime.datetime(2018, 7, 23)



回答4:


In case you have the yearly number of week, just add the number of weeks to the first day of the year.

>>> import datetime
>>> from dateutil.relativedelta import relativedelta

>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)



回答5:


Here's a handy function including the issue with zero-week.



来源:https://stackoverflow.com/questions/17087314/get-date-from-week-number

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