在 Python 中生成日期到一周中的几天? [英] Generating dates to the days of a week in Python?

查看:29
本文介绍了在 Python 中生成日期到一周中的几天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从某个日期(例如: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

这篇关于在 Python 中生成日期到一周中的几天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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