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
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.
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 ).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With