从周数获取日期 [英] Get date from week number
问题描述
请问我的代码有什么问题:
import datetime
d =2013-W26
r = datetime.datetime.strptime(d,%YW%W)
print(r)
显示2013-01-01 00:00:00,谢谢。
星期数不够生成日期;你也需要一周的一天。添加默认值:
import datetime
d =2013-W26
r = datetime.datetime.strptime (d +'-0',%YW%W-%w)
print(r)
-0
和 - %w
模式告诉解析器在该周选择星期日。这将输出:
2013-07-07 00:00:00
pre>
您可以选择自己的工作日,无论最适合您的用例;
%W
模式基于星期一星期,所以也许-1
在这里更好的默认。
请参阅
脚本4中的strftime()
和strptime()
行为部分
与
strptime()
方法一起使用时,%U
%W
仅在指定星期几和年份时用于计算。
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.
解决方案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 + '-0', "%Y-W%W-%w") print(r)
The
-0
and-%w
pattern tells the parser to pick the sunday in that week. This outputs:2013-07-07 00:00:00
You can pick your own weekday, whatever fits your use case best; the
%W
pattern bases weeks from monday, so perhaps-1
is a better default here.See the
strftime()
andstrptime()
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.
这篇关于从周数获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!