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,915
  • 6
  • 30
  • 66
Tek Nath Acharya
  • 1,676
  • 2
  • 20
  • 35

3 Answers3

2
#!/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
  • 336
  • 1
  • 5
2

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
  • 487
  • 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
1

To get a random timezone using zoneinfo:

#!/usr/bin/env python3

import random
import zoneinfo


def get_random_timezone():
    all_timezones = list(zoneinfo.available_timezones())
    random_timezone_key = random.choice(all_timezones)
    return zoneinfo.ZoneInfo(key=random_timezone_key)

# let's try it out...
get_random_timezone()
arcanemachine
  • 571
  • 4
  • 9