Created
February 13, 2013 03:32
-
-
Save cosileone/4942034 to your computer and use it in GitHub Desktop.
Date Localization challenge 118. Unfinished because the final string doesn't get formatted properly -> need tips!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
def formatTime(format): | |
now = datetime.now() | |
for pair in parseTokens("%", format): | |
pair = replaceToken(pair, now) | |
slice1 = format[:pair[0]] | |
slice2 = format[pair[0]+2:] | |
format = slice1 + pair[1] + slice2 | |
print format | |
def parseTokens(t, str): | |
index = str.find("%") | |
occurrences = [] | |
while((index != -1) and (index < len(str) - 1)): | |
occurrences.append((index, str[index+1])) | |
index = str.find("%", index+1) | |
return occurrences | |
def replaceToken(p, now): | |
special_chars = ["l", "s", "m", "h", "H", "c", "d", "M", "y"] | |
if p[1] in special_chars: | |
p = (p[0], translateToken(p[1], now)) | |
return p | |
def translateToken(t, now): | |
if(t == "l"): | |
t = str(now.microsecond / 1000) | |
elif(t == "s"): | |
t = str(now.second) | |
elif(t == "m"): | |
t = str(now.minute) | |
elif(t == "h"): | |
if (now.hour == 0): | |
t = str(12) | |
else: | |
t = str(now.hour % 12) | |
elif(t == "H"): | |
t = str(now.hour) | |
elif(t == "c"): | |
if(now.hour < 12): | |
t = "AM" | |
else: | |
t = "PM" | |
elif(t == "d"): | |
t = str(now.day) | |
elif(t == "M"): | |
t = str(now.month) | |
elif(t == "y"): | |
t = str(now.year) | |
else: | |
print "Error: Token translation not found" | |
return t | |
formatTime("%s.%l") | |
formatTime("%s:%m:%h %M/%d/%y") | |
formatTime("The minute is %m! The hour is %h.") | |
formatTime("%%s") | |
#formatTime("derp%") | |
#formatTime("he % ll %o") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment