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

Generating dates to the days of a week in Python?(在 Python 中生成日期到一周中的几天?)
本文介绍了在 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 中生成日期到一周中的几天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Seasonal Decomposition of Time Series by Loess with Python(Loess 用 Python 对时间序列进行季节性分解)
Resample a time series with the index of another time series(使用另一个时间序列的索引重新采样一个时间序列)
How can I simply calculate the rolling/moving variance of a time series in python?(如何在 python 中简单地计算时间序列的滚动/移动方差?)
How to use Dynamic Time warping with kNN in python(如何在python中使用动态时间扭曲和kNN)
Keras LSTM: a time-series multi-step multi-features forecasting - poor results(Keras LSTM:时间序列多步多特征预测 - 结果不佳)
Python pandas time series interpolation and regularization(Python pandas 时间序列插值和正则化)