如何在 Python 中对日期执行算术运算?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16670601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:19:26  来源:igfitidea点击:

How to perform arithmetic operation on a date in Python?

pythondatetimepython-2.7

提问by atams

I have a date column in csv file say Datehaving dates in this format 04/21/2013and I have one more column Next_Day. In Next_Daycolumn I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013as date then I want 04/22/2013in Next_Day column.

我在 csv 文件中有一个日期列,说Date有这种格式的日期04/21/2013,我还有一列Next_Day。在Next_Day列中,我想填充日期列中提到的日期之后的日期。例如。如果日期列04/21/2013作为日期,那么我想要04/22/2013在 Next_Day 列中。

We can use +1in excel but I don't know how to perform this in Python.

我们可以+1在 excel中使用,但我不知道如何在 Python 中执行此操作。

Please help me in resolving this.

请帮我解决这个问题。

采纳答案by jamylak

Using datetime.timedelta

使用 datetime.timedelta

>>> import datetime
>>> s = '04/21/2013'
>>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1)
>>> print(d.strftime('%m/%d/%Y'))
04/22/2013