-1

I am hoping someone can point me in the right direction in working with dates and timedelta.

my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta. if that is correct, how can I add any number to a date when it is an integer?

any documentation or links would be great - thank you.

code example, my date is as follows:

x = 20100103 (formatted as YYYYMMDD)
antonio_zeus
  • 477
  • 2
  • 11
  • 21
  • 1
    First of all what does it mean to add a number to a date? What is "number"? Is it amount of days? Why are you using integers instead of Python's [`datetime` and `timedelta` types](https://docs.python.org/2/library/datetime.html)? – freakish Jun 14 '16 at 21:35
  • Take a look at [this](http://stackoverflow.com/questions/6871016/adding-5-days-to-date-in-python) – nbryans Jun 14 '16 at 21:35
  • @freakish my apologies, I have edited the original question as you are right, I want to add any number of days to a current date – antonio_zeus Jun 14 '16 at 21:37
  • RTM. https://docs.python.org/2/library/datetime.html#datetime.timedelta – Karoly Horvath Jun 14 '16 at 21:37
  • 1
    @antonio_zeus So ok, you have to convert your date into `datetime` object and "10 days" into `timedelta` object. Then you can add them and Python takes care of all the details of datetime modification. See the documentation I've linked in my previous comment. – freakish Jun 14 '16 at 21:38
  • @freakish that's exactly what I was looking for, the breakdown on what to do to my date (convert to datetime object) and then 10 days (to timedelta object) - ty! – antonio_zeus Jun 14 '16 at 21:42

3 Answers3

4
>>> import datetime
>>> today = datetime.datetime.now().date()
>>> today
datetime.date(2016, 6, 14)
>>> today + datetime.timedelta(days=10)
datetime.date(2016, 6, 24)

There's no need to convert it to a timedelta. Just use the timedelta function, if you want to add days, use days=N, for hours, timedelta(hours=20)

slackmart
  • 4,754
  • 3
  • 25
  • 39
3
x=20100103
x2 = int((datetime.datetime.strptime(str(x),"%Y%m%d") + datetime.timedelta(days=10)).strftime("%Y%m%d"))

to break it down

x=20100103
x_as_datetime = datetime.datetime.strptime(str(x),"%Y%m%d") 
new_datetime = x_as_datetime + datetime.timedelta(days=10) #add your timedelta
x2 = new_datetime.strftime("%Y%m%d") # format it back how you want
int(x2) # if you just want an integer ... 
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1
from datetime import datetime
from datetime import timedelta

StartDate = "20100103"

Date = datetime.strptime(StartDate, "%Y%m%d")
EndDate = Date + timedelta(days=10)
nbryans
  • 1,507
  • 17
  • 24