[Python] Convert time display (str type) using "" "and"'" to seconds (float type) with datetime and timedelta

Overview

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.

1. Convert a string to datetime type using strptime of Datetime

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.

2. Convert to timedelta type, then convert to seconds

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

[Python] Convert time display (str type) using "" "and"'" to seconds (float type) with datetime and timedelta
How to get the date and time difference in seconds with python
I tried to convert datetime <-> string with tzinfo using strftime () and strptime ()
Convert exponential notation float to str in Python
To represent date, time, time, and seconds in Python
How to convert Python # type for Python super beginners: str
0 Convert unfilled date to datetime type with regular expression
How to convert Python # type for Python super beginners: int, float
[Python] Display the elapsed time in hours, minutes, and seconds (00:00:00)
Convert video to black and white with ffmpeg + python + opencv
Determine the date and time format in Python and convert to Unixtime
Linking Python and Arduino to display IME On / Off with LED
Convert list to DataFrame with python
Try to display google map and geospatial information authority map with python
How to calculate "xx time" in one shot with Python timedelta
Challenge to create time axis list report with Toggl API and Python
Try to make foldl and foldr with Python: lambda. Also time measurement
Get and convert the current time in the system local timezone with python
Read CSV file with Python and convert it to DataFrame as it is
Calculate and display standard weight with python
From Python to using MeCab (and CaboCha)
Convert memo at once with Python 2to3
Using Python and MeCab with Azure Databricks
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Fractal to make and play with Python
Convert FX 1-minute data to 5-minute data with Python
How to display python Japanese with lolipop
Receive date type (datetime) with ArgumentParser [python]
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
I'm using tox and Python 3.3 with Travis-CI
Sample to convert image to Wavelet with Python
Format and display time series data with different scales and units with Python or Matplotlib
[Python] Create a list of date and time (datetime type) for a certain period
Execute raw SQL using python data source with redash and display the result
Convert csv, tsv data to matrix with python --using MovieLens as an example
Python datetime How to calculate dates and convert strings strftime, strptime [Definitive Edition]
Three things I was addicted to when using Python and MySQL with Docker
Convert the world time zone time string to Japan time without calculating the time difference with python.
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
Convert DICOM to PNG with Ascending and Descending
Convert PDF to image (JPEG / PNG) with Python
Convert "number" of excel date to python datetime
Convert PDFs to images in bulk with Python
Interactively display algebraic curves with Python and Jupyter
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
How to convert SVG to PDF and PNG [Python]
How to measure execution time with Python Part 1
[Python3] Read and write with datetime isoformat with json
Convert STL to Voxel mesh using Python VTK
How to convert (32,32,3) to 4D tensor (1,32,32,1) with ndarray type
How to handle datetime type in python sqlite3
[Python] Class type and usage of datetime module
[Python] How to compare datetime with timezone added
How to measure execution time with Python Part 2
Convert strings to character-by-character list format with python
Reading, summarizing, visualizing, and exporting time series data to an Excel file with Python
I made a program to convert images into ASCII art with Python and OpenCV