Python:任意日期增加3周 [英] Python: Adding 3 weeks to any date

查看:163
本文介绍了Python:任意日期增加3周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关程序的帮助。

如何在用户可以控制日期的任何给定日期上增加3周(21天)?

I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?

用户将输入日期YYYY-MM-DD。

The user will enter the date YYYY-MM-DD.

在下面,我试图找到连字符并确保只有2个。这是到目前为止,我所要做的只是重复一遍,有人可以告诉我我哪里出了错吗?:

Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:

date = raw_input("Enter date: ")
i = 0
while i <= len(date):
    if date[i] != "-":
    i = i + 1
print date

现在我要选择年,月,日。是否有更简单的方法来执行此操作,因为我需要考虑更改月份等?

Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?

year = date[0:4]
month = date[5:7]
day = date[9:11]

谢谢

推荐答案

使用 datetime 模块添加到任务。您创建一个可识别日期时间的对象,并向其中添加21天的timedelta对象。

Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.

>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00

这篇关于Python:任意日期增加3周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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