0

I am getting a random datetime between two datetimes with following code

start_date = datetime.datetime(2013, 1, 1, tzinfo=pytz.UTC).toordinal()
end_date = datetime.datetime.now(tz=pytz.utc).toordinal()
return datetime.date.fromordinal(random.randint(start_date, end_date))

The problem is that it is not timezone aware.

I have already tried making it timezone aware by using tzinfo=pytz.UTC as seen in the code above but it doesn't work. I guess datetime.date.fromordinal() makes it a naive datetime format.

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • see this answer: http://stackoverflow.com/questions/12626045/pytz-and-astimezone-cannot-be-applied-to-a-naive-datetime – Pynchia Jun 06 '15 at 14:02

1 Answers1

2

If you use datetime.datetime instead of datetime.date in your code then .replace(tzinfo=pytz.utc) works on the result.

To support arbitrary steps (not only 1 day):

#!/usr/bin/env python3
import random
from datetime import datetime, timedelta, timezone

step = timedelta(days=1)
start = datetime(2013, 1, 1, tzinfo=timezone.utc)
end = datetime.now(timezone.utc)
random_date = start + random.randrange((end - start) // step + 1) * step

Note: if start uses a timezone with a non-fixed utc offset then call tz.normalize() at the end.

jfs
  • 399,953
  • 195
  • 994
  • 1,670