pythonloopstimewhile-looptimecodes

How to split and access time in individual digits? [hh:mm:ss]


I want to split the time into individual digits. For Eg. We usually look at time in HH: MM: SS


Solution

  • It is possible like this:

    from datetime import datetime
    
    
    # We get the current time.
    d = datetime.now()
    time_now = d.strftime("%H:%M:%S")
    print("time:", time_now)
    
    # We divide the received time into elements.
    time_split = [int(t) for t in time_now if t != ":"]
    print(time_split)
    
    time: 17:08:39
    [1, 7, 0, 8, 3, 9]
    

    Where H1= time_split[0] etc. Or you can create a dictionary with the variables you need:

    var_list = ("h1", "h2", "", "m1", "m2", "", "s1", "s2")
    time_dict = {v: int(t) for v, t in zip(var_list, time_now) if t != ":"}
    print(time_dict)
    
    {'h1': 1, 'h2': 7, 'm1': 0, 'm2': 8, 's1': 3, 's2': 9}