Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date format in Python in Windows

In a sample code given to me for my homework, this line appears:

date_format = locale.nl_langinfo(locale.D_FMT)

But in Windows that line returns the following error:

File "C:\Users\Shadark\Dropbox\IHM\P3\p3_files\www\cgi-bin\todolist.py", line 11, in <module>
date_format = locale.nl_langinfo(locale.D_FMT)
AttributeError: 'module' object has no attribute 'nl_langinfo'

I've read about using localeconv but I only read about it being used currency or numbers. Any idea on uses for the purpose of my code sample or other kind of function?

Thanks in advance.

like image 699
Shadark Avatar asked Nov 15 '12 16:11

Shadark


People also ask

How do I print a date in DD MMM 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.

How do I get the current date format in Python?

today() The today() method of date class under DateTime module returns a date object which contains the value of Today's date. Returns: Return the current local date.

How do I extract a date format from a string in Python?

Given a string, the task is to write a Python program to extract date from it. Input : test_str = "gfg at 2021-01-04" Output : 2021-01-04 Explanation : Date format string found. Input : test_str = "2021-01-04 for gfg" Output : 2021-01-04 Explanation : Date format string found.


1 Answers

Your problem is probably the fact that locale.nl_langinfo doesn't appear to be available in Windows Python 2.7.x (I don't see it in my copy of Windows 64-bit Python 2.7.3). Looking at the docs at http://docs.python.org/2.7/library/locale.html#locale.nl_langinfo, they specifically say:

This function is not available on all systems, and the set of possible options might also vary across platforms.

Once you've set the locale up with something along the lines of:

locale.setlocale(locale.LC_ALL, 'english')

Then calls to some_date.strftime() will use correct locale specific formatting and strings. So if you want the date in string format, call some_date.strftime('%x') replace the %x with %X for time or %c for both. The full list of strftime formats are documented here.

>>> d = datetime.datetime.now()
... for loc in ('english', 'german', 'french'):
...     locale.setlocale(locale.LC_ALL, loc)
...     print loc, d.strftime('%c -- %x -- %X -- %B -- %A')
english 11/15/2012 4:10:56 PM -- 11/15/2012 -- 4:10:56 PM -- November -- Thursday
german 15.11.2012 16:10:56 -- 15.11.2012 -- 16:10:56 -- November -- Donnerstag
french 15/11/2012 16:10:56 -- 15/11/2012 -- 16:10:56 -- novembre -- jeudi
14: 'French_France.1252'
like image 154
John Gaines Jr. Avatar answered Oct 13 '22 04:10

John Gaines Jr.