I have 4 cases of time string as follow:
- s = "July 5, 2016, 12:04 a.m."
- s = "July 5, 2016, 7 a.m."
- s = "July 5, 2016, midnight."
- s = "July 5, 2016, noon."
I want to convert string to timestamps. Based on this question, I need to declare 4 cases of pattern. I am looking forward to improve my solution.
The following code is my solution:
import time
import datetime
s1 = "July 5, 2016, 12:04 a.m."
s2 = "July 5, 2016, 7 a.m."
s3 = "July 5, 2016, midnight."
s4 = "July 5, 2016, noon."
def convert(timestring):
# clear dot
timestring = timestring.replace(".","")
# convert s3 and s4 to s1 and s2
timestring = timestring.replace("midnight", "12:00 am") if "midnight" in timestring else timestring
timestring = timestring.replace("noon", "12:00 pm") if "noon" in timestring else timestring
result = None
try:
# try to match s2
print(timestring)
result = time.mktime(datetime.datetime.strptime(timestring, "%B %d, %Y, %I %p").timetuple())
except ValueError as e:
try:
result = time.mktime(datetime.datetime.strptime(timestring, "%B %d, %Y, %I:%M %p").timetuple())
except ValueError as e:
print(e)
print(result)
def main():
convert(s1)
convert(s2)
convert(s3)
convert(s4)
if __name__ == '__main__':
main()