# Time Code with Microsecond Conversion

The function below converts a time code into seconds, while maintaining the decimal value (fractions of seconds). The time code fed to this function will always contain microseconds. This currently works, but I'd be interested to see how it could be improved/simplified.

def Second_Conversion(x): #Takes a string such as "2:22:04.996304"
HMS = x.split(':')
SF = x.split('.')
Full_HMS = x[0:7]
Split_HMS = Full_HMS.split(':')

Full_Units = int(Split_HMS[0]) * 3600 + int(Split_HMS[1]) * 60 + int(Split_HMS[2])

Second_Fractions = int(SF[1])
Converted_Seconds_Fractions = Second_Fractions /1000000
print(Converted_Seconds_Fractions)

Final_Time = Full_Units + Converted_Seconds_Fractions
print(Final_Time)

• Thanks for the link Janos! Would you mind explaining how exactly I'm breaking the PEP8? I'm pretty new to Python, and would greatly appreciate any insight you can offer. Thanks again! – Elle Mar 14 '15 at 1:45
• Variable and function names should be snake_case, all lowercase. – janos Mar 14 '15 at 7:21

This section can be simplified as you only print the variables, never work with them:

Second_Fractions = int(SF[1])
Converted_Seconds_Fractions = Second_Fractions /1000000
print(Converted_Seconds_Fractions)

Final_Time = Full_Units + Converted_Seconds_Fractions
print(Final_Time)


Why don't you just do this?

print(int(SF[1]) / 1000000)
print(Full_Units + Converted_Seconds_Fractions)


Also, it isn't good to have magic values in your code. I would probably put the 1000000 value in a variable named with UPPER_CASE naming to show it shouldn't be changed. Python does not have a way to signify constant variables, so that is why you use a different naming convention for them.

Again, I would probably not print from the same method you convert them with. What if you want to get the value from this method sometime without it printing them? You should return the values instead of just printing them, and maybe make a separate method for printing them.

• Thanks so much for the suggestions Hosch250! Funnily enough, I included the print statements in an attempt make the code easier to understand (for this post, actually). The Final_Time variable will be returned, and used elsewhere in the program (I just didn't think including that portion of the code was relevant). Regarding the magic value, I completely overlooked this, and I'll definitely change it. Anyway, thanks again for your help! – Elle Mar 14 '15 at 1:33

I don't know whether you wanted to optimize the code for length or speed or "elegance", but here it is as a one-liner:

def Second_Conversion(x):
return sum(map(lambda i,j: int(i)*j, x.replace('.', ':').split(':'), [3600, 60, 1, 1e-6]))

• Very cool! I'm still pretty new to Python, so I really love seeing the different ways one can approach a problem. Thanks @Nivaead! – Elle Mar 14 '15 at 1:38