Python datetime format like C# String.Format -
i'm trying port application c# python. application allows user choose datetime format using c# string.format datetime formatting. python's datetime formatting not close same, i'm having jump code through few hoops.
is there way python can parse strings yyyy-mm-dd hh-mm-ss
instead of %y-%m-%d %h-%m-%s
?
you can fair distance using simple replacement convert format strings.
_format_changes = ( ('mmmm', '%b'), ('mmm', '%b'), # note: order in list critical ('mm', '%m'), ('m', '%m'), # note: no exact equivalent # etc etc ) def conv_format(s): c, p in _format_changes: # s.replace(c, p) #### typo/braino s = s.replace(c, p) return s
i presume "hoops" means similar. note there complications:
(1) c# format can have literal text enclosed in single quotes (examples in link quoted)
(2) allows single character made literal escaping (e.g.) \
(3) 12- or 24-hour clock stuff may need work (i haven't delved c# spec; comment based similar exercise i've been involved in).
can end writing compiler , byte-code interpreter around gotchas (like m, f, ff, fff, ...).
an alternative @ using ctypes
or similar call c#
rtl directly.
update original code overly simplistic , had typo/braino. following new code shows how address of issues (like literal text, , ensuring literal %
in input doesn't make strftime unhappy). doesn't attempt give accurate answers there's no direct conversion (m, f, etc). places exception raised noted code operates on laissez-faire basis.
_format_changes = ( ('yyyy', '%y'), ('yyy', '%y'), ('yy', '%y'),('y', '%y'), ('mmmm', '%b'), ('mmm', '%b'), ('mm', '%m'),('m', '%m'), ('dddd', '%a'), ('ddd', '%a'), ('dd', '%d'),('d', '%d'), ('hh', '%h'), ('h', '%h'), ('hh', '%i'), ('h', '%i'), ('mm', '%m'), ('m', '%m'), ('ss', '%s'), ('s', '%s'), ('tt', '%p'), ('t', '%p'), ('zzz', '%z'), ('zz', '%z'), ('z', '%z'), ) def cnv_csharp_date_fmt(in_fmt): ofmt = "" fmt = in_fmt while fmt: if fmt[0] == "'": # literal text enclosed in '' apos = fmt.find("'", 1) if apos == -1: # input format broken. apos = len(fmt) ofmt += fmt[1:apos].replace("%", "%%") fmt = fmt[apos+1:] elif fmt[0] == "\\": # 1 escaped literal character. # note graceful behaviour when \ last character. ofmt += fmt[1:2].replace("%", "%%") fmt = fmt[2:] else: # loop done regex "(yyyy)|(yyy)|etc". intok, outtok in _format_changes: if fmt.startswith(intok): ofmt += outtok fmt = fmt[len(intok):] break else: # hmmmm, c# here? # *you* want here? # i'll emit 1 character literal text # , carry on. alternative: raise exception. ofmt += fmt[0].replace("%", "%%") fmt = fmt[1:] return ofmt
tested following extent:
>>> cnv_csharp_date_fmt import cnv_csharp_date_fmt cv >>> cv("yyyy-mm-dd hh:mm:ss") '%y-%m-%d %i:%m:%s' >>> cv("3pcts %%% yyyy-mm-dd hh:mm:ss") '3pc%p%s %%%%%% %y-%m-%d %i:%m:%s' >>> cv("'3pcts' %%% yyyy-mm-dd hh:mm:ss") '3pcts %%%%%% %y-%m-%d %i:%m:%s' >>> cv(r"3pc\t\s %%% yyyy-mm-dd hh:mm:ss") '3pcts %%%%%% %y-%m-%d %i:%m:%s' >>>
Comments
Post a Comment