strptime - dates formatted differently on different computers
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Dec 10 21:07:51 EST 2012
On Mon, 10 Dec 2012 16:36:37 -0500, Dave Angel wrote:
> When accepting input from a user, consider their environment. Perhaps
> they're in a different timezone than your program (or your native
> location), or use some other ordering for the date (for example, the
> Japanese sensibly put year first, then month, then day. Other regions
> have different conventions. If you can't detect the user environment,
> then you'd better tell them yours. For example,by prompting for day,
> month, and year separately.
+1
In a nutshell, you can't know ahead of time what the user will be using
as a date format, or what their computer will be set to use as date
format. Unless you control the operating system and can force a
particular date format, you are at the OS's mercy.
Having stated that the problem is hard, what's the solution? I expect
that it will depend on the OS. Presumably under Windows there is some way
of asking Windows "What is the current date format?". I defer to Windows
users for that. On Linux, and probably Mac OS X, I think this is the
right way to get the system's preferred date format:
py> import locale
py> locale.setlocale(locale.LC_ALL, '') # You MUST call this first.
'en_AU.utf8'
py> locale.nl_langinfo(locale.D_FMT)
'%d/%m/%y'
You can pass that string on to strptime:
py> import time
py> time.strptime("11/12/13", '%d/%m/%y')
time.struct_time(tm_year=2013, tm_mon=12, tm_mday=11, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=6, tm_yday=346, tm_isdst=-1)
--
Steven
More information about the Python-list
mailing list