I'm trying to parse a string to a date object on Google App Engine. The string is formatted locally and I thereby either need to set the locale setting before parsing the string or find a third part module that does international formatting.
In Google App Engine I found that only the "C" locale is supported, which made my initial implementation useless:
datestring = "20. oktober 2013, 18:43"
locale.setlocale(locale.LC_ALL, 'da_DK.UTF-8')
date = datetime.datetime.strptime(datestring, "%d. %B %Y, %H:%M")
Threw error:
Error: locale emulation only supports "C" locale
In my search for a third part module I found Babel. It has formatting features from data objects to string but I can't see that it works the other way around, and I can't find another module that does the trick.
Is there any other solution I haven't thought of, or do I need to go make my own module for this?
Thanks!
Related
In robot framework, the current supported keyword to get timezone is:
${month} Get Current Date result_format=%B%Y
which will return: July 2017
The question is how to get current date from other country and locale?
as example in Vietnam should return: Tháng Bảy 2017
and Thailand should return : กรกฎาคม พ.ศ. 2560
Unfortunately, python doesn't have good built-in support for formatting dates in locales other than the current one. You can temporarily switch locales, but that's not a great solution.
You can use the the Babel package to format the dates, though it doesn't provide precisely the same value you expect -- the case is slightly different.
For example, you could create a keyword that dates a month, year, and locale, and returns the formatted version.
First, create a python file named CustomKeywords.py with the following contents:
# CustomKeywords.py
import datetime
from babel.dates import format_date
class CustomKeywords:
def get_date_for_locale(self, locale, year, month=1, day=1):
d = datetime.date(int(year), int(month), int(day))
return format_date(d, "MMMM Y", locale=locale)
Next, import this library into your test case and then call get date for locale to get the date for a given locale:
*** Settings ***
Library CustomKeywords.py
*** Test Case ***
Vietnamese
${date}= get date for locale vi_VN 2017 7
Should be equal ${date} tháng bảy 2017
Thailand
${date}= get date for locale th_TH 2017 7
Should be equal ${date} กรกฎาคม 2017
In the Robot Framework Datetime library the concept of changing the TimeZone is not present. The Robot Framework Custom Timestamp functions rely on the underlying Python datatime.strptime function. This function uses the python Locale for it's formatting.
As this has now become a more general Python problem, I've searched SO and found this particular SO answer to fulfill the criteria to create a custom Python Keyword for Robot Framework that would allow changing the Locale and thus determine the output.
Is there a method to retrieve time zone names in another language?
In Python, if I do something like this:
for tz in pytz.common_timezones_set :
print tz
The result is in English, but what if I would like to have it in Spanish or Arabic?
You can use babel package
import pytz
from babel.dates import get_timezone_location
for tz in pytz.common_timezones_set:
print(get_timezone_location(tz, locale='es'))
No, unfortunately there are no translations for the timezone names. The names are part of the Olson timezone database (not part of Python or pytz). New ones are added from time to time, so any potential translation project would have to stay in sync with that database.
pytz.common_timezones_set returns a set of timezone ids in the tz database. They are designed to be human readable but they are not translatable.
PyICU provides access to the localized timezone names:
>>> from datetime import datetime
>>> import icu
>>> df = icu.DateFormat.createDateTimeInstance(icu.DateFormat.SHORT, icu.DateFormat.FULL, icu.Locale.getFrance())
>>> df.format(datetime.now(icu.ICUtzinfo.getDefault()))
'27/01/2015 21:01:01 heure normale d’Europe centrale'
Coming quite late but I ran into a similar issue lately, and ended up creating my own package l18n for that purpose. It is available here : https://pypi.org/project/l18n/
It provides translations files for human-readable places and timezones used in pytz. Most of the translations are automatically fetched from the CLDR database, but there are always a few of them missing. For the moment only translation files for English and French are available. Feel free to contact me (create an issue on the packages's repo https://github.com/tkhyn/l18n) or follow the step-by-step procedure here if you want to add translations for your language.
From Facebook Graph API I retrieve events which have the start_time set as string with the following format: "2012-10-12T23:30:00+0200". When location is specified it returns also the event object contains also the timezone (e.g.: "Europe/Rome").
I simply would like to check which events are upcoming (newer than "now").
I wonder if there is a way to do so without using pytz, which is not installed by default in Django. For deployment, the more portable the solution is the better.
You can use the built-in datetime module after a quick parse of the returned string (using "-", "T", and "+" as tokens).
Here is a quick reference to the documentation : http://docs.python.org/library/datetime.html
Note : this module handles timezone (search for tzone in the page).
I have found answers to question like this one helpful but not complete for my problem.
I have a form where the user automatically produces a date. I would like to store that as a date time.
I don't need any of the information after the seconds, but I cannot find a datetime.datetime.strptime code to translate the remaining stuff. So I would either like a strptime code that works for python2.7 on google app engine, or a string editing trick for removing the extra information that is not needed.
date-from-user='2012-09-22 07:36:36.333373-05:00'
You can slice your string to only select the first 19 characters:
>>> datefromuser='2012-09-22 07:36:36.333373-05:00'
>>> datefromuser[:19]
'2012-09-22 07:36:36'
This let's you parse the date without having to bother with the microseconds and timezone.
Do note that you probably do want to parse the timezone too though. You can use the iso8601 module to handle the whole format, without the need to slice:
>>> import iso8601
>>> iso8601.parse_date(datefromuser)
datetime.datetime(2012, 9, 22, 7, 36, 36, 333373, tzinfo=<FixedOffset '-05:00'>)
The iso8601 module is written in pure python and works without problems on the Google App Engine.
Python Docs would be a good place to start. strptime() would be your best option.
import datetime
datefromuser = '2012-09-22 07:36:36.333373-05:00'
datetime.datetime.strptime(datefromuser.split(".")[0], "%Y-%m-%d %H:%M:%S")
2012-09-22 07:36:36
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.
Something like:
from datetime import datetime
from django.shortcuts import render_to_response
def my_view(request):
ws_date_as_string = ... get the webservice date
the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
return render_to_response('my_template.html', {'date':the_date})
As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.
This doesn't deal with the Django tag, but the strptime code is:
d = strptime("2009-06-11 17:02:09+0000", "%Y-%m-%d %H:%M:%S+0000")
Note that you're dropping the time zone info.