在 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
Add 1 day to my date in Python
提问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 datetime
modulefrom the standard library. Load the date string via strptime()
, use timedelta
to 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'