I am trying to transform a time variable that uses strings and integres in one column into one more friendly. For example my time variable looks like: 30m 32s
I want a variable in format 30:32 or a variable with number of seconds. Thanks.
CodePudding user response:
To transform your time variable into a more friendly format, you can use Python's datetime module.
Here is an example of how you can do this:
from datetime import datetime, timedelta
# Split the time string into minutes and seconds
time_parts = time_string.split(' ')
minutes = int(time_parts[0][:-1])
seconds = int(time_parts[1][:-1])
# Create a timedelta object representing the time
time = timedelta(minutes=minutes, seconds=seconds)
# Convert the timedelta object to a string in the desired format
formatted_time = str(time).split('.')[0]
print(formatted_time) # Outputs '0:30:32'
If you want to get the number of seconds instead of a formatted string, you can use the total_seconds method of the timedelta object:
total_seconds = time.total_seconds()
print(total_seconds) # Outputs 1832.0
I hope this helps! Let me know if you have any questions.
CodePudding user response:
I'm not sure I fully understood the question, but the following will split your string on the space then separate out the individual minutes / seconds.
def formatTime(time: str):
minutes, seconds = time.split(' ') # Split on the space character
minutes_val = minutes.split('m')[0] # Separate the minutes value
seconds_val = seconds.split('s')[0] # Separate the seconds value
return f"{minutes_val}:{seconds_val}" # Return the formatted string
CodePudding user response:
try this:
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
output:
year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:3