Search code examples
pythontimezonepytz

pytz: getting all timezones, where now is specific time


In DB I have table (User), which store timezone (as a string value, for ex.: "Europe/Oslo") for that user. Now, I need to get all Users, where local time now is for ex.: 9AM.

Is there any good way of doing this, w/o making loop over all Users? If pytz is able to return list of timezones, where for now time is 9AM, I can use simple IN SQL statement.


Solution

  • import datetime
    import pytz
    
    now = datetime.now(pytz.utc)
    # datetime.datetime(2012, 6, 8, 10, 31, 58, 493905, tzinfo=<UTC>)
    
    [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 9]
    # ['Atlantic/Cape_Verde']
    
    [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 12]
    # returns a list of 45 timezones, 'Europe/Oslo' included