简体   繁体   中英

Get random timezone aware datetime in Python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM