1

I need some random time zone but don't know how to do it using python. The time zone should be in GMT and in following format (Example).

(GMT-XX:YY) Place Name
DennisLi
  • 3,470
  • 5
  • 23
  • 51
Tek Nath
  • 1,374
  • 1
  • 18
  • 34

2 Answers2

1

You can try something like this.

#!/usr/bin/python3
import  pytz
import random
from datetime import datetime
randZoneName = random.choice(pytz.all_timezones)
randZone=datetime.now(pytz.timezone(randZoneName))
offset=randZone.strftime('%z')
print("(GMT%s:%s) %s"%(offset[:3],offset[3:],randZoneName))
Mayhem
  • 467
  • 2
  • 5
  • 13
  • Beat me to it. Just take care, `pytz.all_timezones`, and `pytz.common_timezones`, as also mentioned [here](https://stackoverflow.com/questions/13866926/is-there-a-list-of-pytz-timezones), have the complete list of available timezones. That means *they are not equally distributed*, as you might have multiple names for one timezone, and less names for others. If you want a uniform distribution from GMT-12 to GMT+12, you could pick a random number between -12, 12 *and then* choose a named `pytz.timezone` – hyperTrashPanda Jul 04 '19 at 10:35
0
#!/usr/bin/env python3
import random
import pytz
from datetime import datetime, timedelta, timezone

tz = set(pytz.all_timezones_set)
tz = list(tz)
selected_tz = pytz.timezone(tz[random(0,tz.length)])
step = timedelta(days=1)
start = datetime(2013, 1, 1, tzinfo=selected_tz)
end = datetime.now(selected_tz)
random_date = start + random.randrange((end - start) // step + 1) * step
Billi
  • 116
  • 4