Reputation: 1
I want to split the time for having the hours, the minutes, and the second on a list. But with the datetime module I can't. This is my code :
heure = datetime.now().time()
heure = heure.split(":")
print(heure)
Thank you in advance.
Upvotes: 0
Views: 2839
Reputation: 655
There is a method called datetime.strftime
, which also uses datetime
like the method you tried to use. We change the string input to an integer using int()
.
from datetime import datetime as dt # Import datetime module
now = dt.now()
# Using strftime to get the string into a global variable
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
hour = now.strftime("%H")
minute = now.strftime("%M")
second = now.strftime("%S")
microseconds = now.strftime("%f")
# Turning the variables into integers
year = int(year)
month = int(month)
day = int(day)
hour = int(hour)
minute = int(minute)
second = int(second)
microseconds = int(microseconds)
# Putting the variables into a list
heure = [year, month, day, hour, minute, second, microseconds]
print(heure)
Indexes of the heure list
Index 0: Year
Index 1: Month
Index 2: Day
Index 3: Hour
Index 4: Minute
Index 5: Seconds
Index 6: Microseconds (1/1 000 000th of a second)
The only problem is that the time is in UTC, sadly, I do NOT know how to convert it using
datetime.now()
.
Upvotes: 2
Reputation: 380
You need to convert the heure
to string with the str()
and then split it.
heure = datetime.now().time()
heure = str(heure).split(":")
print(heure)
Upvotes: 0
Reputation: 71454
heure
is a datetime.time
object, not a string. It already splits out the various components of the time as properties. Do:
>>> hms = [heure.hour, heure.minute, heure.second]
>>> hms
[8, 9, 33]
Upvotes: 1