2
\$\begingroup\$

I'm converting python's very un user-friendly strftime date time directives to user-friendly formats so that users of an API will know how to format a date if they send an invalid format.

My thinking is that %Y-%m-%d is platform specific to Python where as even non-programmers would know what to send if we told them dates must be in the format YYYY-MM-DD. I guess my biggest issue with this code is I feel like this might already be inbuilt with strftime or python's datetime lib. If not, can this be improved or is this good enough?

import re

directives = {
    "%d": "DD",
    "%-d": "D",
    "%m": "MM",
    "%-m": "M",
    "%y": "YY",
    "%Y": "YYYY",
    "%H": "HH",
    "%-H": "H",
    "%I": "hh",
    "%-I": "h",
    "%p": "A",
    "%M": "mm",
    "%-M": "m",
    "%S": "ss",
    "%-S": "s"
}

format = "%Y-%m-%d"

pattern = re.compile('|'.join(directives.keys()))
nice_format = pattern.sub(lambda x: directives[x.group()], format)

print nice_format
\$\endgroup\$
3
  • 2
    \$\begingroup\$ I'm not 100%, but I don't think "[strftime] is platform specific to Python". Python gets a lot of things from C, and C++ has an implementation too. Browsing seems to show C and PHP have an implementation too... \$\endgroup\$
    – Peilonrayz
    Commented Jan 23, 2018 at 15:20
  • \$\begingroup\$ "Good enough" for what purpose? \$\endgroup\$ Commented Jan 23, 2018 at 17:08
  • \$\begingroup\$ @Peilonrayz ok that's good. Doesn't change the purpose which is hopefully explained above - outputting a nicer format of date placeholders for users to understand. And, I guess by good enough, I mean can it be simplified or shortened. \$\endgroup\$
    – Dan Bovey
    Commented Jan 23, 2018 at 17:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.