I was scraping a certain thing, and I was having trouble processing the elapsed time, so I made a note. Do you know the notation of such a stopwatch? "X'yy" z "means" x minutes yy.z seconds ". What I want to do this time is to convert this character string (str type) to seconds (float type) using python. For example The conversion is "1'45" 5 "-> 105.5 seconds.
In the program, the character string type of python is described by 'hoge'
or " hoge "
, but this time notation "x'yy" z "is"'"," "" in the character string. Will be included. In such a case, the python string is handled by using \
, which is written as 'x \'yy" z'
.
If this is made into a datetime type using strptime, it will be as follows.
from datetime import datetime
# %M is minutes,%S is seconds,%f is microseconds
strtime = '1\'45"5' #String
t = datetime.strptime(strtime, '%M\'%S"%f')
print('t:', t)
print('type:', type(t))
# Output
# t: 1900-01-01 00:01:45.500000
# type: <class 'datetime.datetime'>
With this alone, since datetime is a date type, it will be 0:01:45:500,000 microseconds on January 1, 1900. This time, I want to treat it as "time" instead of date, so this is not enough. Therefore, it is converted to timedelta type.
timedelta stands for "time" instead of "date", as it is used for adding and subtracting dates and times. However, since it is not possible to convert directly from the character string, the datetime type is returned. The conversion from datetime type to timedelta type is as follows.
from datetime import timedelta
t_delta = timedelta(
seconds=t.second, #Datetime type t seconds are stored
microseconds=t.microsecond, #Contains microseconds of datetime type t
minutes=t.minute, #Datetime type t minutes are stored
)
print('t_delta:', t_delta)
print('type:', type(t_delta))
# Output
# t_delta: 0:01:45.500000
# type: <class 'datetime.timedelta'>
You can see that the timedelta type is not a date but is treated as 1 minute 45 seconds 5 as a time.
Finally, 1 minute 45 seconds 5 is converted to seconds only.
Of course, you can write programming manually, but timedelta has a method called total_seconds ()
, which can be converted to seconds in one shot!
tdl2sec = t_delta.total_seconds()
print(tdl2sec)
print(type(tdl2sec))
#Output
# 105.5
# <class 'float'>
Achieved a happy goal! !!
Recommended Posts