如何在python中创建一个表示设定天数的日期对象

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

how to create a date object in python representing a set number of days

pythondatetime

提问by avorum

I would like to define a variable to be a datetime object representing the number of days that is entered by the user. For example.

我想将一个变量定义为一个表示用户输入的天数的日期时间对象。例如。

numDays = #input from user
deltaDatetime = #this is what I'm trying to figure out how to do
str(datetime.datetime.now() + deltaDatetime)

This code would print out a datetime representing 3 days from today if the user entered 3 as their input. Any idea how to do this? I'm completely lost as to an effective approach to this problem.

如果用户输入 3 作为他们的输入,此代码将打印出表示从今天起 3 天的日期时间。知道如何做到这一点吗?我完全不知道解决这个问题的有效方法。

EDIT: Because of how my system is set up, the variable storing the "deltaDatetime" value must be a datetime value. As I said in the comments, something like 3 days becomes Year 0, January 3rd.

编辑:由于我的系统是如何设置的,存储“deltaDatetime”值的变量必须是一个日期时间值。正如我在评论中所说,像 3 天这样的事情变成了 0 年,1 月 3 日。

回答by Mark Ransom

deltaDateTime = datetime.timedelta(days=3)

回答by zzzirk

It's fairly straightforward using timedelta from the standard datetime library:

使用标准日期时间库中的 timedelta 相当简单:

import datetime
numDays = 5   # heh, removed the 'var' in front of this (braincramp)
print datetime.datetime.now() + datetime.timedelta(days=numDays)

回答by alecxe

Use timedelta:

使用时间增量

from datetime import datetime, timedelta

days = int(raw_input())
print datetime.now() + timedelta(days=days)