DjangoBB

Django based forum engine

  • You are not logged in.

#1 May 1, 2012 19:53:58

loarf
Registered: 2011-04-29
Posts: 5
Reputation: +  0  -
Profile   Send e-mail  

Time zones

Could someone explain to me how the time zones users' set in their profiles are supposed to work. Times are always displayed in the time zone specified in the TIME_ZONE setting in the projects settings.py regardless of the time zone users specify. Is there any way around this?

Offline

#2 May 3, 2012 13:30:53

slav0nic
DjangoBB Developer
From: Ukraine
Registered: 2009-10-25
Posts: 382
Reputation: +  5  -
Profile   Send e-mail  

Time zones

time_zone in profile was reserved time ago, now django 1.4 officially support it (http://djangobb.org/ticket/74).

maybe it will be fixed after migration to bootstrap2 and other major changes

Offline

#3 Aug. 31, 2012 15:40:40

jedie
From: germany
Registered: 2012-07-12
Posts: 160
Reputation: +  1  -
Profile   Send e-mail  

Time zones

related to this: https://github.com/jedie/DjangoBB/compare/master…timezone




Some of my Projects:
* Migrate phpBB to DjangoBB with django-phpBB3
* DjangoBB github repro and information about my changes
* PyLucid CMS written in Django: http://www.pylucid.org/

Offline

#4 Aug. 31, 2012 19:23:31

jedie
From: germany
Registered: 2012-07-12
Posts: 160
Reputation: +  1  -
Profile   Send e-mail  

Time zones

btw. about selecting the time zone:

I search the internet for a better list for:

TZ_CHOICES = [(float(x[0]), x[1]) for x in (
    (-12, '-12'), (-11, '-11'), (-10, '-10'), (-9.5, '-09.5'), (-9, '-09'),
    (-8.5, '-08.5'), (-8, '-08 PST'), (-7, '-07 MST'), (-6, '-06 CST'),
    (-5, '-05 EST'), (-4, '-04 AST'), (-3.5, '-03.5'), (-3, '-03 ADT'),
    (-2, '-02'), (-1, '-01'), (0, '00 GMT'), (1, '+01 CET'), (2, '+02'),
    (3, '+03'), (3.5, '+03.5'), (4, '+04'), (4.5, '+04.5'), (5, '+05'),
    (5.5, '+05.5'), (6, '+06'), (6.5, '+06.5'), (7, '+07'), (8, '+08'),
    (9, '+09'), (9.5, '+09.5'), (10, '+10'), (10.5, '+10.5'), (11, '+11'),
    (11.5, '+11.5'), (12, '+12'), (13, '+13'), (14, '+14'),
)]

…and found many links, but the most are unusable (because contains too many cities). Best hits are:
http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx
http://www.davidsemporium.co.uk/worldclock.html

Then i played with pytz. You can get a list of all timezones. But there are too many region/cities, too:
import collections
from datetime import datetime
import pytz
def get_shortest(l, max=3):
    """
    >>> get_shortest(["aa","bbb","c","dd"])
    ['c', 'aa', 'dd']
    >>> get_shortest(["aa","b","cc","d"], 2)
    ['b', 'd']
    """
    l = sorted(l, key=lambda x: len(x))
    return l[:max]
def get_human_timezones(max_cities=3, max_countries=4):
    human_timezones = {}
    utc = pytz.timezone('UTC')
    utc_now = datetime.now()#.replace(tzinfo=utc)
    timezone_data = {}#collections.defaultdict(list)
    for zone_name in pytz.common_timezones:
        tz = pytz.timezone(zone_name)
        dt = tz.localize(utc_now)
        offset = dt.strftime("%z")
        #~ utcoffset = tz._utcoffset # timedelta object
        #~ offset = utcoffset.total_seconds() / 60
        if offset not in timezone_data:
            timezone_data[offset] = [dt.strftime("%Z")]
        timezone_data[offset].append(zone_name)
    for utc_offset, data in timezone_data.items():
        tz_acronym = data[0]
        places = data[1:]
        places_dict = collections.defaultdict(list)
        for place in places:
            if "/" in place:
                country, cities = place.split("/",1)
                places_dict[country].append(cities)
        human_places = []
        for country, cities in sorted(places_dict.items()):
            cities = get_shortest(cities, max=max_cities)
            human_places.append(
                "%s:%s" % (country, ",".join(cities))
            )
        human_places = "%s - %s" % (
            tz_acronym, " - ".join(human_places)
        )
        human_timezones[utc_offset] = human_places
    return human_timezones
if __name__ == "__main__":
    human_timezones = get_human_timezones(max_cities=3, max_countries=4)
    for utc_offset, human_places in sorted(human_timezones.items(), key=lambda x: int(x[0])):
        print utc_offset, human_places

Will produced this:
-1100 SST - Pacific:Niue,Midway,Pago_Pago
-1000 HST - Pacific:Tahiti,Honolulu,Johnston - US:Hawaii
-0930 MART - Pacific:Marquesas
-0900 HADT - America:Adak - Pacific:Gambier
-0800 AKDT - America:Nome,Sitka,Juneau - Pacific:Pitcairn - US:Alaska
-0700 PDT - America:Dawson,Phoenix,Tijuana - Canada:Pacific - US:Arizona,Pacific
-0600 CST - America:Boise,Belize,Denver - Canada:Mountain - Pacific:Easter,Galapagos - US:Mountain
-0500 EST - America:Lima,Bogota,Cancun - Canada:Central - US:Central
-0430 VET - America:Caracas
-0400 AST - America:Aruba,Cuiaba,Guyana - Antarctica:Palmer - Canada:Eastern - US:Eastern
-0300 BRT - America:Bahia,Belem,Thule - Antarctica:Rothera - Atlantic:Bermuda,Stanley - Canada:Atlantic
-0230 NDT - America:St_Johns - Canada:Newfoundland
-0200 WGST - America:Godthab,Noronha,Miquelon - Atlantic:South_Georgia
-0100 CVT - Atlantic:Cape_Verde
+0000 GMT - Africa:Lome,Accra,Dakar - America:Danmarkshavn,Scoresbysund - Atlantic:Azores,Reykjavik,St_Helena
+0100 CET - Africa:Lagos,Tunis,Bangui - Atlantic:Faroe,Canary,Madeira - Europe:Dublin,Jersey,Lisbon
+0200 CAT - Africa:Cairo,Ceuta,Harare - Arctic:Longyearbyen - Europe:Oslo,Rome,Malta
+0300 EAT - Africa:Asmara,Kampala,Nairobi - Antarctica:Syowa - Asia:Aden,Gaza,Amman - Europe:Kiev,Riga,Minsk - Indian:Comoro,Mayotte,Antananarivo
+0400 GST - Asia:Dubai,Muscat,Tbilisi - Europe:Moscow,Samara,Volgograd - Indian:Mahe,Reunion,Mauritius
+0430 AFT - Asia:Kabul,Tehran
+0500 MAWT - Antarctica:Mawson - Asia:Baku,Oral,Aqtau - Indian:Maldives,Kerguelen
+0530 IST - Asia:Colombo,Kolkata
+0545 NPT - Asia:Kathmandu
+0600 VOST - Antarctica:Vostok - Asia:Dhaka,Almaty,Bishkek - Indian:Chagos
+0630 MMT - Asia:Rangoon - Indian:Cocos
+0700 DAVT - Antarctica:Davis - Asia:Hovd,Omsk,Bangkok - Indian:Christmas
+0800 WST - Antarctica:Casey - Asia:Macau,Brunei,Harbin - Australia:Perth
+0845 CWST - Australia:Eucla
+0900 TLT - Asia:Dili,Seoul,Tokyo - Pacific:Palau
+0930 CST - Australia:Darwin,Adelaide,Broken_Hill
+1000 DDUT - Antarctica:DumontDUrville - Asia:Yakutsk - Australia:Currie,Hobart,Sydney - Pacific:Guam,Chuuk,Saipan
+1030 LHST - Australia:Lord_Howe
+1100 MIST - Antarctica:Macquarie - Asia:Sakhalin,Vladivostok - Pacific:Efate,Kosrae,Noumea
+1130 NFT - Pacific:Norfolk
+1200 NZST - Antarctica:McMurdo,South_Pole - Asia:Anadyr,Magadan,Kamchatka - Pacific:Fiji,Wake,Nauru
+1245 CHAST - Pacific:Chatham
+1300 WST - Pacific:Apia,Fakaofo,Enderbury
+1400 LINT - Pacific:Kiritimati

Not really needfull…

So i search for a way to sort by population and found a simple text file database here: https://www.maxmind.com/app/worldcities
It has 3173959 items and 43183 cities with population count. Looks like:
Country,City,AccentCity,Region,Population,Latitude,Longitude
ad,aixas,AixĂ s,06,,42.4833333,1.4666667
ad,aixirivali,Aixirivali,06,,42.4666667,1.5
ad,aixirivall,Aixirivall,06,,42.4666667,1.5
ad,aixirvall,Aixirvall,06,,42.4666667,1.5
...

So i played with it and build this:
# coding:utf-8
import time
import collections
from datetime import datetime
import pytz
def get_shortest(l, max=3):
    """
    >>> get_shortest(["aa","bbb","c","dd"])
    ['c', 'aa', 'dd']
    >>> get_shortest(["aa","b","cc","d"], 2)
    ['b', 'd']
    """
    l = sorted(l, key=lambda x: len(x))
    return l[:max]
def get_biggest(cities, population_data, max=2):
    """
    >>> get_biggest(["A", "B", "C"], {"b":1, "c":2})
    ['C', 'B']
    """
    cities = sorted(cities, key=lambda x: population_data.get(x.lower(), 0), reverse=True)
    return cities[:max]
def build_human_places(places_dict, population_data, max_chars):
    """
    >>> build_human_places(
    ...     {"r1": ["c1", "c2", "c3"], "r2": ["C1", "C2"], "r3": ["x1"]},
    ...     {"c2":10, "x1":2, "c3": 20},
    ...     max_chars=12)
    'c3,C2,x1,c2'
    """
    # places_dict: {"r1": ["c1", "c2"], "r2": ["C1", "C2"]}
    city_data = []
    for cities in places_dict.values():
        cities = sorted(cities, key=lambda x: population_data.get(x.lower(), 0), reverse=True)
        city_data.append(cities)
    human_places = []
    has_cities = True
    for index in xrange(20):
        has_cities = False
        for cities in city_data:
            #~ print index, cities
            try:
                city = cities[index]
            except IndexError:
                pass
            else:
                if (len(",".join(human_places)) + len(city)) >= max_chars:
                    #return ",".join(human_places)
                    break
                human_places.append(city)
                has_cities = True
        if not has_cities:
            break
    return ",".join(human_places)
def get_human_timezones(population_data, max_chars):
    human_timezones = {}
    utc = pytz.timezone('UTC')
    utc_now = datetime.now()#.replace(tzinfo=utc)
    timezone_data = {}#collections.defaultdict(list)
    for zone_name in pytz.common_timezones:
        tz = pytz.timezone(zone_name)
        dt = tz.localize(utc_now)
        offset = dt.strftime("%z")
        #~ utcoffset = tz._utcoffset # timedelta object
        #~ offset = utcoffset.total_seconds() / 60
        if offset not in timezone_data:
            timezone_data[offset] = [dt.strftime("%Z")]
        timezone_data[offset].append(zone_name)
    for utc_offset, data in timezone_data.items():
        tz_acronym = data[0]
        places = data[1:]
        places_dict = collections.defaultdict(list)
        for place in places:
            if "/" in place:
                country, cities = place.split("/",1)
                places_dict[country].append(cities)
        human_places = build_human_places(places_dict, population_data, max_chars)
        human_timezones[utc_offset] = (tz_acronym, human_places)
    return human_timezones
def city_data(filepath, min_population=10000000):
    """
    Data file from: https://www.maxmind.com/app/worldcities
    """
    start_time = time.time()
    next_status = start_time + 0.25
    population_data = {}
    with file(filepath, "r") as f:
        skip_count = 0
        for line in f:
            country,city,accentcity,region,population,latitude,longitude = line.split(",")
            if not population:
                continue
            try:
                population = int(population)
            except ValueError:
                continue
            if time.time() > next_status:
                next_status = time.time() + 1
                print "Adds %i cities and %i cities are too small" % (len(population_data), skip_count)
            if population<min_population:
                skip_count += 1
                continue
            population_data[city.lower()] = population
    print "Adds %i cities and %i cities are too small" % (len(population_data), skip_count)
    return population_data
if __name__ == "__main__":
    import doctest
    print doctest.testmod()
    #~ sys.exit()
    population_data = city_data("worldcitiespop.txt", min_population=1)
    #~ population_data = {}
    human_timezones = get_human_timezones(population_data, max_chars=70)
    for utc_offset, human_places in sorted(human_timezones.items(), key=lambda x: int(x[0])):
        print utc_offset, human_places

result is:
-1100 ('SST', 'Midway,Niue,Pago_Pago')
-1000 ('HST', 'Hawaii,Honolulu,Johnston,Rarotonga,Tahiti')
-0930 ('MART', 'Marquesas')
-0900 ('HADT', 'Adak,Gambier')
-0800 ('AKDT', 'Anchorage,Alaska,Pitcairn,Juneau,Sitka,Nome,Metlakatla,Yakutat')
-0700 ('PDT', 'Pacific,Phoenix,Arizona,Tijuana,Pacific,Hermosillo,Vancouver')
-0600 ('CST', 'Mountain,Managua,Mountain,Easter,Guatemala,Galapagos,Tegucigalpa')
-0500 ('EST', 'Central,Bogota,Central,Chicago,Guayaquil,Monterrey,Winnipeg,Cancun')
-0430 ('VET', 'Caracas')
-0400 ('AST', 'Eastern,Palmer,Toronto,Eastern,Montreal,Manaus,Port-au-Prince,Detroit')
-0300 ('BRT', 'Atlantic,Rothera,Fortaleza,Stanley,Recife,Bermuda,Montevideo,Maceio')
-0230 ('NDT', 'Newfoundland,St_Johns')
-0200 ('WGST', 'Miquelon,South_Georgia,Godthab,Noronha')
-0100 ('CVT', 'Cape_Verde')
+0000 ('GMT', 'Reykjavik,Danmarkshavn,Abidjan,Azores,Scoresbysund,Dakar,St_Helena')
+0100 ('CET', 'London,Canary,Kinshasa,Dublin,Faroe,Casablanca,Lisbon,Madeira,Algiers')
+0200 ('CAT', 'Budapest,Longyearbyen,Harare,Stockholm,Johannesburg,Prague,Lubumbashi')
+0300 ('EAT', 'Istanbul,Syowa,Antananarivo,Nairobi,Baghdad,Kiev,Comoro,Mogadishu')
+0400 ('GST', 'Samara,Mahe,Dubai,Volgograd,Mauritius,Yerevan,Moscow,Reunion,Tbilisi')
+0430 ('AFT', 'Kabul,Tehran')
+0500 ('MAWT', 'Mawson,Kerguelen,Karachi,Maldives,Tashkent,Baku,Dushanbe,Samarkand')
+0530 ('IST', 'Colombo,Kolkata')
+0545 ('NPT', 'Kathmandu')
+0600 ('VOST', 'Vostok,Chagos,Yekaterinburg,Almaty,Dhaka,Bishkek,Qyzylorda,Thimphu')
+0630 ('MMT', 'Cocos,Rangoon')
+0700 ('DAVT', 'Davis,Christmas,Jakarta,Bangkok,Novosibirsk,Omsk,Novokuznetsk')
+0800 ('WST', 'Casey,Perth,Shanghai,Manila,Chongqing,Singapore,Harbin,Taipei,Urumqi')
+0845 ('CWST', 'Eucla')
+0900 ('TLT', 'Palau,Tokyo,Seoul,Irkutsk,Dili,Jayapura,Pyongyang')
+0930 ('CST', 'Darwin,Adelaide,Broken_Hill')
+1000 ('DDUT', 'DumontDUrville,Brisbane,Chuuk,Yakutsk,Melbourne,Guam,Sydney,Hobart')
+1030 ('LHST', 'Lord_Howe')
+1100 ('MIST', 'Macquarie,Noumea,Vladivostok,Efate,Sakhalin,Guadalcanal,Kosrae,Pohnpei')
+1130 ('NFT', 'Norfolk')
+1200 ('NZST', 'McMurdo,Auckland,Magadan,South_Pole,Fiji,Anadyr,Funafuti,Kamchatka')
+1245 ('CHAST', 'Chatham')
+1300 ('WST', 'Apia,Enderbury,Fakaofo,Tongatapu')
+1400 ('LINT', 'Kiritimati')

I put the biggest cities, but from every region.

IMHO i can enhanced it like:
* use the biggest cities, but at least one from a region…




Some of my Projects:
* Migrate phpBB to DjangoBB with django-phpBB3
* DjangoBB github repro and information about my changes
* PyLucid CMS written in Django: http://www.pylucid.org/

Offline

#5 Aug. 31, 2012 21:06:59

jedie
From: germany
Registered: 2012-07-12
Posts: 160
Reputation: +  1  -
Profile   Send e-mail  

Time zones

Beside “how to select own timezone”: What should be done with these information?

How should times be handled in DjangoBB generally?

Think that is no easy question. Maybe it makes at most sence to store everything in UTC and display them as UTC and use JavaScript to add a title with a calculated local time and maybe a “how old information” (This post was created since 5 days)




Some of my Projects:
* Migrate phpBB to DjangoBB with django-phpBB3
* DjangoBB github repro and information about my changes
* PyLucid CMS written in Django: http://www.pylucid.org/

Offline

#6 Aug. 31, 2012 23:48:20

jedie
From: germany
Registered: 2012-07-12
Posts: 160
Reputation: +  1  -
Profile   Send e-mail  

Time zones

I have found a better solution:

Why not remove completely the timezone from profile and send the current user timezone in every post form by inserting the current UTC offset via JavaScript in a hidden field.

Get this information is easy:

    var now = new Date();
    var time_zone_offset = -now.getTimezoneOffset() / 60;
Put it into a hidden field is also easy.

What i don't know: Does every browser generate this in the same way?




Some of my Projects:
* Migrate phpBB to DjangoBB with django-phpBB3
* DjangoBB github repro and information about my changes
* PyLucid CMS written in Django: http://www.pylucid.org/

Edited jedie (Aug. 31, 2012 23:49:16)

Offline

#7 Sept. 5, 2012 13:17:47

jedie
From: germany
Registered: 2012-07-12
Posts: 160
Reputation: +  1  -
Profile   Send e-mail  

Time zones

Other, maybe simpler solution: Store everything in UTC (without any timezone info). Render every times in UTC. On the client a JavaScript convert the UTC times into local times. Here, we also need no timezone info in the user profile.

Also interesting: Convert absolute UTC times into relative times by JavaScript, like timesince it does, but on the client. The benefit is, that the page content can be cacheable a very long time, without to update the timesince values.
Maybe display e.g. post time like:

<span title="Aug. 31, 2012 23:45:21">4 days, 6 hours</span>




Some of my Projects:
* Migrate phpBB to DjangoBB with django-phpBB3
* DjangoBB github repro and information about my changes
* PyLucid CMS written in Django: http://www.pylucid.org/

Edited jedie (Sept. 5, 2012 13:22:03)

Offline

#8 June 8, 2018 04:22:58

WizliamboW
Registered: 2018-06-08
Posts: 1
Reputation: +  0  -
Profile   Send e-mail  

Time zones

cialis tadalafil 20mg price kerobbs.cgi?page=
cialis over counter
cheapest cialis generic
<a href="http://cialis-walmart.shop">generic cialis at walmart
</a> - cialis 20 mg 8 table e-mail address
levitra cialis cialis

Offline

#9 Aug. 11, 2018 04:38:27

JalonRog
Registered: 2018-08-11
Posts: 1
Reputation: +  0  -
Profile   Send e-mail  

Time zones

levitra 5mg topics
levitra 20mg
possible levitra effects sperm production
<a href="http://levitragtr.com">levitra 20 mg price
</a> - levitra 20mg tablets last post
levitra 20mg online msn messenger

Offline

#10 Aug. 12, 2018 08:38:14

FamesJob
Registered: 2018-08-12
Posts: 1
Reputation: +  0  -
Profile   Send e-mail  

Time zones

levitra reviews 20 mg search engines
levitra 20 mg
levitra 20mg coupons location
<a href="http://levitragls.com">levitra 20 mg price
</a> - compare levitra,levitra and levitra
levitra 3.99

Offline

Board footer

Moderator control

Powered by DjangoBB

Lo-Fi Version