Richard Bucker

time time python time time

Posted at — Sep 3, 2011

I wonder how many bugs there are out there because people use “time” incorrectly. I think I discovered a design flaw, implementation detail or just a really crazy thing to watch out for that I have no idea where to go with it except here.I’ve written this code a hundred times:date = time.strftime('%m/%d/%Y')time = time.strftime('%H:%M:%S')This code behaves all the time except!!! At midnight of whatever timezone you are in. Consider that if the strftime() function that is computing/formatting the date took place yesterday and the strftime() for the time variable took place tomorrow. You would get seriously affected results.While you would think that you could do this:now = time.time()date = now.strftime('%m/%d/%Y')time = now.strftime('%H:%M:%S')It feels right and it might work in some languages. But not here. When now is assigned time.time(), it is of type float. And therefore you cannot apply the function strftime() to a float. You need an instance of time.Swinging back around, If there is a date class that returns date and a time class that returns time; why would the time class have a strftime() function that would accept date format params and vice versa?This works:now = = now.strftime('%m/%d/%Y')time = now.strftime('%H:%M:%S')In order to state the obvious, the first line gets the system time from the clock; then using the copy of the time in order to format the date and time strings.PS: date and time are the proper names of python modules. Their usage in this exact┬ácontext is questionable and could cause errors. But it worked… for now.