toonarmycaptain
toonarmycaptain

Reputation: 2331

Get system country location while offline

I'm looking to accept date input into a script and running into the conundrum of how to differentiate between 040507 // 04052007 and 050407 // 05042007 when user intends April 5th, 2007 (or May 4th, 2007). The US tends to follow the first form, but other countries the second.

I know I can use IP/GPS in some instances, but I'm looking for a method that works offline, maybe from system location/language?

I'm primarily looking for a Windows solution, but surely others will be useful in future/to others.

NB I'm not considering timezone a good option, as different countries in the same timezone can use different conventions.

Upvotes: 0

Views: 284

Answers (2)

Superspork
Superspork

Reputation: 413

Judging by your date formats, I think your user manually enters the date. Unfortunately, locality will have little to do with how it is entered. I am in the US but prefer to input my date with the full year.

A simple way would be to force a standard or accept either way and test for which was entered.

def test():
    while True:
        testdate = input()
        if testdate.isdigit() and len(testdate) == 6:
            #do something
            break
        elif testdate.isdigit() and len(testdate) == 8:
            #do something
            break
        else: 
            print("Please enter correct format")

This would check to make sure only digits are entered and then checks the length to determine which format was used.

You could force a standard by specifying “ddmmyyyy” and only accept an 8 digit input.

If I’m wrong on how the date is given, let me know and I’ll update accordingly.

EDIT:

If you want to guess the user’s format by determining their location, you can use the locale module.

import locale

print(locale.getlocale())

Output:

('en_US', 'UTF-8')

Another way using locale is to check the international currency symbol of the locale.

import locale

locale.setlocale(locale.LC_ALL, "")
print(locale.localeconv()['int_curr_symbol'])

Output:

USD

Here is a list of currency codes: https://www.ibm.com/support/knowledgecenter/en/SSZLC2_7.0.0/com.ibm.commerce.payments.developer.doc/refs/rpylerl2mst97.htm

Upvotes: 1

user3483203
user3483203

Reputation: 51185

You could always check the OS default language, using getdefaultlocale(), and you could use that to guide how you parse dates:

>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'cp1252')

This wouldn't be exact, as I would enter dates the same way no matter what locale my computer is using, but it could give you a starting point.

Upvotes: 1

Related Questions