Handling locale date string conversion?
I have a date as a string in the form „dd/mm/yyyy“ and need to convert it to the form „dd. MMMM yyyy“ so that the verbose month is printed out in German.
Now, because we still have the locale bug in Pythonista ...
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'de') Traceback (most recent call last): File "<string>", line 1, in <module> File "/var/containers/Bundle/Application/4D653312-79ED-4473-B63A-522E9EA8C250/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/locale.py", line 599, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting >>> locale.setlocale(locale.LC_ALL, 'de_DE') Traceback (most recent call last): File "<string>", line 1, in <module> File "/var/containers/Bundle/Application/4D653312-79ED-4473-B63A-522E9EA8C250/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/locale.py", line 599, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting
... I guess I‘m forced to find a workaround. So I opted for the
objc_utilmodule and tried this (variable
gebDatumholds the initial date string in the above mentioned format):
from objc_util import * NSDateFormatter = ObjCClass('NSDateFormatter') dateFormatter = NSDateFormatter.alloc().init() NSLocale = ObjCClass('NSLocale') deLocale = NSLocale.alloc().initWithLocaleIdentifier_(ns('de')) dateFormatter.setLocale_(deLocale) NSDate = ObjCClass('NSDate') date = NSDate.alloc().init() dateFormatter.setDateFormat_('dd/MM/yyyy') date = dateFormatter.dateFromString_(gebDatum) dateFormatter.setDateFormat_('dd. MMMM yyyy') gebDatumVerbose = dateFormatter.stringFromDate_(date)
Now when I want to print out the variable
gebDatumVerboseI get the error
must be str, not ObjCInstance.
Any help / hint / explanation / other (shorter) solution for my problem?
Thanks a lot!
objc_util methods usually return ObjCInstances. In this case NSString.
For NSString,you can use
strto convert to a python string.
@metawops, Hi. I guess you are using the App Store version of Pythonista. Anyway at least in the beta version of Pythonista, ships with a 3rd party lib called arrow, I am not sure if its in the App Store Version yet. Its a lib for helping with dates/times etc. I have a feeling it would solve your problem.
But you can check by trying to import it i.e
If the import fails meaning its not installed, If have StaSh installed you could pip install arrow.
Here is a link to the arrow docs.
@JonB Awesome, that did the trick! I‘m glad my code works now exactly as I wanted it to work! 😃 Thanks so much for that missing puzzle piece!!
@Phuket2 Hi, I‘m on the beta program, too, and will have a look at this library! Thanks for the hint! 😃