Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling international dates in python

I have a date that is either in German for e.g,

2. Okt. 2009

and also perhaps as

2. Oct. 2009

How do I convert this into an ISO datetime (or Python datetime)?

Solved by using this snippet:

for l in locale.locale_alias:
    worked = False
    try:
        locale.setlocale(locale.LC_TIME, l)
        worked = True
    except:
        worked = False
    if worked: print l

And then plugging in the appropriate for the parameter l in setlocale.

Can parse using

import datetime
print datetime.datetime.strptime("09. Okt. 2009", "%d. %b. %Y")
like image 977
geejay Avatar asked Aug 19 '09 11:08

geejay


People also ask

How are dates handled in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

How do you write date in dd mm yyyy format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


2 Answers

http://docs.python.org/library/locale.html

The datetime module is already locale-aware.

It's something like the following

# German locale
loc = locale.setlocale(locale.LC_TIME, ("de","de"))
try:
     date = datetime.date.strptime(input, "%d. %b. %Y")
except:
     # English locale
     loc = locale.setlocale(locale.LC_TIME, ("en","us"))
     date = datetime.date.strptime(input, "%d. %b. %Y")
        
like image 110
S.Lott Avatar answered Oct 22 '22 03:10

S.Lott


Very minor point about your code snippet: I'm no Python expert but I'd consider the whole "flag to check for success + silently swallowing all exceptions" to be bad style.

try/expect/else does what you want in a cleaner way, I think:

for l in locale.locale_alias:
    try:
        locale.setlocale(locale.LC_TIME, l)
    except locale.Error: # the doc says setlocale should throw this on failure
        pass
    else:
        print l
like image 3
Nicolas Lefebvre Avatar answered Oct 22 '22 03:10

Nicolas Lefebvre