Pick numbers with decimals from a xlsx spreadsheet and convert in hours in python

Asked

Viewed 58 times

0

This number 25.0555556, if formatted in Excel [h]:mm:ss, represents 601:20:00, how to get Python to read in hours. I work with a spreadsheet that looks for a report from a system and converts it into a spreadsheet, and at the time of checking how it is in the spreadsheet the value is in numerical format, I need to do the formatting in hours. Now I am passing this data from the spreadsheet to Python and the value is formatted as number and with decimal places.

Access the test files in Drive here

  • Welcome to [en.so]! You have posted an image of the code and/or error message. Although it sounds like a good idea, it’s not! One of the reasons is that if someone wants to answer the question, they can’t copy the code and change something inside. Click on the [Edit] link and put the code/error as text. See more about this in these links - Manual on how NOT to ask questions, Post Error Message as Picture

  • Okay, as I can’t describe by the fact that I can’t manipulate the file, I decided to take the image.

1 answer

0


When you do the math, you can see that the number "25.05555556" which corresponds to "601:20" hours is expressed in days.

The class datetime.timedelta do Python can accept entry in days, such as float, and do the accounts for seconds - automatically (or you can only do some divisions). From the total seconds it is easy to get the amounts of hours, minutes and seconds using the operator // entire division)

import datetime

period = datetime.timdelta(days=25.0555556)
hours = period.total_seconds() // 3600
minutes = (period.total_seconds() % 3600) // 60
seconds = (period.total_seconds() % 60) 

final = f"{hours}:{minutes}:{seconds}"

If in your reading the "25..." is coming as a string with a "," instead of "." the quickest way is to use the method replace of the string to exchange the , for . before to convert the value to numeric with float - but if it goes to an app that will stay in production and can work files formatted otherwise, can be most interesting to use the module locale for always make the replacement the right way - check out the answer here: How to use Python comma instead of a dot

  • It worked, but I cannot insert the value of this result obtained in the final variable within a dataframe. When I pass the information the column value is 0:0 and not 601:20. Rf['HT'] = final, what shows in the dataframe is 0:0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.