简体   繁体   English

Python - 从星期几、年份和周数中获取日期

[英]Python - Get date from day of week, year, and week number

I have: a week number a day of week a year I want to find the date from that.我有: 一周数 一年中的一天 我想从中找到日期。 How to do it in Python?如何在 Python 中做到这一点?

eg 2020 week1 Saturday Expected output 01/04/2020例如 2020 周 1 周六 预计产量 01/04/2020

you can use ISO 8601 year and -week directives:您可以使用 ISO 8601 年和周指令:

from datetime import datetime

s = '2020 week1 Saturday'

dt = datetime.strptime(s, '%G week%V %A')       

print(dt.strftime('%m/%d/%Y'))
# 01/04/2020

Another way of doing it (Based on @MrFuppes's answer) using standard C implementation:使用标准 C 实现的另一种方法(基于@MrFuppes 的回答):

s = '2020 week0 Saturday'
dt = datetime.strptime(s, '%Y week%W %A')
print(dt.strftime('%m/%d/%Y'))

Bare in mind that the weekdays as well as the weeks - start in zero.请记住,工作日和周 - 从零开始。

Python 3.8 added the fromisocalendar() method, which is even more intuitive. Python 3.8 添加了 fromisocalendar() 方法,更加直观。

from datetime import datetime
dt =datetime.fromisocalendar(2020, 1, 6)
print(dt.strftime('%m/%d/%Y'))
# 01/04/2020

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM