How can I get random time zone in python

Question:

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
Asked By: Tek Nath Acharya

||

Answers:

#!/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
Answered By: Billi

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))
Answered By: Mayhem

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()
Answered By: n_moen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.