Home>

How to process strings (time) using Python.

Hour: MM: SS.ssssss. There is time data in the form of a character string. When displaying this, do not display if the tenths of hours, minutes, and seconds are 0. I want to do it.
For example, if the data is "05: 32: 56.234544", I would like to display it as "5:32:56".

This data is taken from a CSV file using Pandas, so now

import pandas as pd
df = pd.read_csv ('CSV_file')
time = df.iat [0,0]


It has a shape like In contrast,

if time [0] == "0":
    reg_time = time [1: 2] + "hours" + time [3: 5] + "minutes" + time [6: 8] + "seconds"


If I want to repeat the if statement for each slice of hours, minutes, and seconds, and to support a format that contains multiple 0s such as `` 02: 12: 01.12345 '', use logical operators to Increasing (time [0] == time [3] =="0").

If that happens, the if-else statement will be a reasonable amount. Is there a way to make it a little easier?

  • Answer # 1

    (1) If there is no problem reading the 0th column as time series data

    df = pd.read_csv ('csv_file', parse_dates = [0])
    d = df.iat [0,0]
    print ("{} hour {} minute {} second" .format (d.hour, d.minute, d.second))
    # 5:32:56

    (2) If you want to read the 0th column as character string data

    df = pd.read_csv ('csv_file')
    d = pd.to_datetime (df.iat [0,0])
    print ("{} hour {} minute {} second" .format (d.hour, d.minute, d.second))
    # 5:32:56
    What about

    ?

  • Answer # 2

    Set to a number (int).

    time = "05: 32: 56.234544"
    print ("{} hour {} minute {} second" .format (int (time [0: 2]), int (time [3: 5]), int (time [6: 8])))
    # =>5:32:56