1

I need to write a python code that generates a random date between 1/1/2014 and 12/31/2014, this will be stored as the beginning date. I then need to have an end date that ends 3 days after the beginning date. I've tried multiple ways of doing this but cant figure out how to get the end date. Please help!

def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))

    ptime = stime + prop * (etime - stime)

    return time.strftime(format, time.localtime(ptime))


def Order_Date(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y', prop)

date_1 = Order_Date("1/1/2014", "12/31/2014", random.random())

def Due_Date(end_date):
    end_date = date_1 + datetime.timedelta(days=3)
    return end_date

print (date_1)
print(Due_Date)
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
Matthew
  • 33
  • 3
  • 1
    Have you considered starting at 1/1/2014 and merely adding a random number of days (<=365) to it? Then add 3 days to that. – user2585435 Nov 13 '15 at 05:40
  • possible duplicate of [Adding 5 days to Date in python](http://stackoverflow.com/questions/6871016/adding-5-days-to-date-in-python) – Ravichandra Nov 13 '15 at 06:17

2 Answers2

2

I've tried multiple ways of doing this but cant figure out how to get the end date.

With datetime.timedelta(days=3). You can add timedeltas to dates:

import datetime as dt
import random

date_format = '%m/%d/%Y'

start_date = dt.datetime.strptime('1/1/2014', date_format)
end_date = dt.datetime.strptime('12/31/2014', date_format)

time_delta = end_date - start_date
rand_days = random.randint(0, time_delta.days)
rand_time_delta = dt.timedelta(days=rand_days)

random_date = start_date + rand_time_delta
print(random_date.strftime(date_format))
random_end_date = random_date + dt.timedelta(days=3)
print(random_end_date.strftime(date_format))

--output:--
09/26/2014
09/29/2014

And if the random_date is 12/31/2014, then the end date will be 01/03/2015, which you can see by setting rand_days = 364.

7stud
  • 46,922
  • 14
  • 101
  • 127
0

Using timedelta it's simple to add three days on to your start date. If you don't want the date going past 12/31/2014 then you'll want to subtract three days off your range. You can also reduce your code quite a bit which should make the entire thing easier to understand:

from datetime import datetime, timedelta
import random

def randDate(y,m,d):
    s = datetime(y, m, d)
    e = s + timedelta(days=3)
    return ("{:%m/%d/%Y}\n{:%m/%d/%Y}".format(s,e))

y = random.randint(2014, 2014) # range for year
m = random.randint(1, 12) # range for month
d = random.randint(1, 28) # range for day

print(randDate(y,m,d))

https://docs.python.org/2/library/datetime.html

l'L'l
  • 44,951
  • 10
  • 95
  • 146