从周数获取日期 [英] Get date from week number

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

问题描述

请问我的代码有什么问题:

  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() 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.

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

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