avorum
avorum

Reputation: 2293

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

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.

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.

Upvotes: 5

Views: 23240

Answers (3)

zzzirk
zzzirk

Reputation: 1582

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

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

Upvotes: 10

alecxe
alecxe

Reputation: 473763

Use timedelta:

from datetime import datetime, timedelta

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

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308111

deltaDateTime = datetime.timedelta(days=3)

Upvotes: 4

Related Questions