Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strftime a date object in a different locale? [duplicate]

I have a date object in python and I need to generate a time stamp in the C locale for a legacy system, using the %a (weekday) and %b (month) codes. However I do not wish to change the application's locale, since other parts need to respect the user's current locale. Is there a way to call strftime() with a certain locale?

like image 565
MagerValp Avatar asked Sep 03 '13 13:09

MagerValp


People also ask

What can I use instead of Strftime?

The strftime is obsolete and DateTime::format() provide a quick replacement and IntlDateFormatter::format() provied a more sophisticated slution.

What does datetime Strftime do?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Returns : It returns the string representation of the date or time object.

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

What is the data type return values from Strftime ()?

The strftime() method returns a string representing date and time using date, time or datetime object.


1 Answers

The example given by Rob is great, but isn't threadsafe. Here's a version that works with threads:

import locale import threading  from datetime import datetime from contextlib import contextmanager   LOCALE_LOCK = threading.Lock()  @contextmanager def setlocale(name):     with LOCALE_LOCK:         saved = locale.setlocale(locale.LC_ALL)         try:             yield locale.setlocale(locale.LC_ALL, name)         finally:             locale.setlocale(locale.LC_ALL, saved)  # Let's set a non-US locale locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')  # Example to write a formatted English date with setlocale('C'):     print(datetime.now().strftime('%a, %b')) # e.g. => "Thu, Jun"  # Example to read a formatted English date with setlocale('C'):     mydate = datetime.strptime('Thu, Jun', '%a, %b') 

It creates a threadsafe context manager using a global lock and allows you to have multiple threads running locale-dependent code by using the LOCALE_LOCK. It also handles exceptions from the yield statement to ensure the original locale is always restored.

like image 153
Daniel Avatar answered Sep 21 '22 08:09

Daniel