Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Adding 3 weeks to any date

Tags:

python

date

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?

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

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] 

thanks

like image 509
monica Avatar asked Mar 04 '11 04:03

monica


People also ask

How do you calculate weeks in Python?

YOu can use the isocalender function from the datetime module to get the current week. Create the object of the date first, then call isocalender() on this object. This returns a 3-tuple of Year, Week number and Day of Week.

How do I get last week's startdate and Enddate in Python?

You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).


2 Answers

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 
like image 93
Senthil Kumaran Avatar answered Sep 24 '22 13:09

Senthil Kumaran


You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.

import datetime  date = raw_input("Enter date: ") aDate = datetime.datetime.strptime(date,"%Y-%m-%d") threeWeeks = datetime.timedelta(weeks = 3)  print aDate + threeWeeks 

See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.

like image 25
Alex Q Avatar answered Sep 22 '22 13:09

Alex Q