在 Python 中为我的日期添加 1 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37089765/
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-19 18:49:25  来源:igfitidea点击:

Add 1 day to my date in Python

pythondate

提问by timko.mate

I have the following date format:

我有以下日期格式:

year/month/day

In my task, I have to add only 1 day to this date. For example:

在我的任务中,我只需为此日期添加 1 天。例如:

date = '2004/03/30'
function(date)
>'2004/03/31'

How can I do this?

我怎样才能做到这一点?

回答by alecxe

You need the datetimemodulefrom the standard library. Load the date string via strptime(), use timedeltato add a day, then use strftime()to dump the date back to a string:

您需要标准库中的datetime模块。通过 加载日期字符串strptime()用于timedelta添加日期,然后用于strftime()将日期转储回字符串:

>>> from datetime import datetime, timedelta
>>> s = '2004/03/30'
>>> date = datetime.strptime(s, "%Y/%m/%d")
>>> modified_date = date + timedelta(days=1)
>>> datetime.strftime(modified_date, "%Y/%m/%d")
'2004/03/31'