-2

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

  • I want to break it down and access both the H, M, and S separately. Like HH should be accessible as H1 [the first digit] and H2 [the second digit] and so on for minutes and seconds.

  • Please note I am looking for real-time values of the broken variables.

Enos jeba
  • 72
  • 1
  • 3
  • 10

1 Answers1

2

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}
Сергей Кох
  • 1,417
  • 12
  • 6
  • 13