Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created August 22, 2012 05:55
Show Gist options
  • Save theY4Kman/3422689 to your computer and use it in GitHub Desktop.
Save theY4Kman/3422689 to your computer and use it in GitHub Desktop.
Formats a datetime object, allowing for a dash modifier to be used, stripping leading zeros from a value
def dateformat(dt, format='%-I:%m %p, %A, %B %-d, %Y'):
# Remove leading zeros if the identifier has a dash in front of it
# Implemented in Python, as in strftime it's platform-dependent
if format.find('%-') != -1:
compiled = ''
i = 0
length = len(format)
fmt = None
fmt_remove_leading = False
while i < length:
c = format[i]
if fmt is None:
if c == '%':
fmt = '%'
else:
compiled += c
else:
if c == '-' and fmt == '%':
fmt_remove_leading = True
elif c.isdigit():
fmt += c
elif c.isdigit() or c in '_^': # Accounts for GNU C flags
fmt += c
fmt_compiled = dt.strftime(fmt)
if fmt_remove_leading:
fmt_compiled = fmt_compiled.lstrip('0')
compiled += fmt_compiled
fmt = None
fmt_remove_leading = False
else:
compiled += fmt
fmt = None
fmt_remove_leading = False
i += 1
compiled += fmt or ''
return compiled
else:
return dt.strftime(format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment