skip to Main Content

when I run the following script

import matplotlib.pyplot as plt
import datetime as dt
date = dt.datetime.strptime('02-Jan-2008 10:09:00', '%d-%b-%Y %H:%M:%S')
print(date)
fig = plt.figure()
date2 = dt.datetime.strptime('02-Jan-2008 10:09:00', '%d-%b-%Y %H:%M:%S')
print(date2)

in my anaconda python 3.8.13, I receive the following message

2008-01-02 10:09:00
Traceback (most recent call last):
File "./prova.py", line 17, in
date2 = dt.datetime.strptime(’02-Jan-2008 10:09:00′, ‘%d-%b-%Y %H:%M:%S’)
File "/home/grieco/anaconda3/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/home/grieco/anaconda3/lib/python3.8/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data ’02-Jan-2008 10:09:00′ does not match format ‘%d-%b-%Y %H:%M:%S’

Note that date and date2 are exactly the same command. For a reason that is not known to me, when I call the command plt.figure(), the date deconding process switches to Spanish (the language on which my ubuntu was installed). Even if I close the figure, the problem persists. I did not yet find a way to control it. Can you please help me on that?

I expect the same output, instead I receive an error

2

Answers


  1. Chosen as BEST ANSWER

    Thank you Furas. The problem is solved, but... If I put the code line

    locale.setlocale(locale.LC_ALL, 'en_GB.utf-8')
    

    before I call

    plt.figure()
    

    after this call, the setting goes back to the previous one. This is a little bit boring when you have a recursive generation of figures in a loop, since you must call it during the entire loop. Best regards


  2. You can use module locale to change it in code

    import locale
    import datetime 
    
    print('current:', locale.setlocale(locale.LC_ALL))
    print( datetime.datetime.today().strftime('%d-%b-%Y %H:%M:%S') )
    
    
    print('new:', locale.setlocale(locale.LC_ALL, 'en_GB.utf-8'))
    print(datetime.datetime.today().strftime('%d-%b-%Y %H:%M:%S') )
    

    On Linux you can use locale -a to see all allowed values.
    If you don’t have en_GB.UTF-8 then you may have to install it in system.


    BTW:

    Some programs allow to set value directly before executing code (ie. before ls)

    LANG=gb_GB.UTF-8 ls -al
    LANG=pl_PL.UTF-8 ls -al
    

    Second line displays ls in Polish language if you have it installed.

    You can also use C (for programing language C) which can be useful to sort elements in different order.

    LANG=C ls -al
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search