在 Python 中生成日期到一周中的几天?

2022-01-11 00:00:00 python date calendar

问题描述

我需要从某个日期(例如:2015/10/22)生成一周中的星期一的日期.并生成接下来几天的日期:周一、周二、周三、周四、周五、周六、周日.

I need to generate a date of Monday of a week from a date (example: 2015/10/22). And generate the dates for the next days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.

Java 中的示例:(初始日期 = 2015/10/22)

Example in Java: (initial date = 2015/10/22)

//星期一:

date.set (Calendar.DAY_OF_WEEK, Calendar.MONDAY);

//添加第二天(星期二)

// Add the next day (Tuesday)

date.add (Calendar.DATE, 1);

//添加第二天(星期三):

// Add the next day (Wednesday):

date.add (Calendar.DATE, 1);

如何在 Python 中做到这一点?

How can I do this in Python?


解决方案

在python中使用timedelta函数更简单

Its easier in python using timedelta function

import datetime

mydate = datetime.datetime(2015, 10, 22, 00, 00, 00, 00)
mymondaydate = mydate - datetime.timedelta(days=mydate.weekday())
mytuesdaydate = mymondaydate + datetime.timedelta(days=1)

print(mydate)
print(mymondaydate)
print(mytuesdaydate)

诀窍是使用 weekday() 函数.来自文档

The trick is the use of weekday() function. From documentation

date.weekday()- 以整数形式返回星期几,其中星期一为 0,星期日为 6.

date.weekday() - Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

所以从当前日期中减去它得到该周的星期一的日期

So subtracting it from current date gives the date of Monday of that week

相关文章