Search code examples
linuxparsingdatetimecommand-linelocale

How to parse a date that has been formatted with different locale


My very smart android phone has produced emails where the date field is formatted with the german locale, e.g. Date: Di., 20 Dez. 2011 23:28:49 +0100. I switched the phone to english to stop it doing this but a number of emails have been written already.

Some other mail program can't handle this because it doesn't have all those locales installed. As a result it set the main date-time to Thu Jan 1 01:00:00 1970 and the emails appear to disappear when I sort by date :-( So I want to fix those emails by rewriting the header. But how can I parse the german date? the date command supports locales on output (date +%c) but seems to ignore the locale on input:

$ date -d "08 Dec 2015"
Tue Dec  8 00:00:00 CET 2015
$ LC_TIME=de_DE.utf8 date -d "08 Dez 2015"
date: invalid date ‘08 Dez 2015’

Any ideas?


Solution

  • If you have Python and a de locale installed, one way would be to call

    % python /path/to/convert.py "08 Dez 2015"
    2015-12-08 00:00:00
    

    where convert.py is this python script:

    import sys, locale, datetime as DT
    locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
    print(DT.datetime.strptime(sys.argv[1], '%d %b %Y'))