Reputation: 13
How do I get hour and seconds separate using this..
localtime = time.asctime(time.localtime(time.time()))
print(localtime)
This results in this..
Thu Oct 11 17:23:28 2018
I just need to know how to get the hour and seconds separate, and if that's not possible with localtime() then how else could I do it?
I'm not that good at coding but am trying to work on a project and can't find any informative documentation on what I need.
Upvotes: 0
Views: 2359
Reputation: 29
import time
secondVariable=time.localtime()[5]
hourVariable=time.localtime()[3]
Upvotes: 0
Reputation: 101
You can use the built in split function, which splits strings into array elements by checking for patterns. Default is ' ', e.g.
'abc def'.split()
will return
['abc', 'def']
So, applying this:
localtime = localtime.split()
will return:
['Thu','Oct','11','17:23:28','2018']
we want to extract the 4th element of the array, and arrays start at 0, so:
localtime = localtime[3]
this returns:
'17:23:28'
now, we need to split again, this time the ':' character:
localtime = localtime.split(':')
this returns:
['17','23','28']
now, for the last part:
extract the individual values:
hour = localtime[0]
minute = localtime[1]
second = localtime[2]
Upvotes: 0
Reputation: 8843
The time.strftime
function is what you're after:
Convert a tuple or
struct_time
representing a time as returned bygmtime()
orlocaltime()
to a string as specified by the format argument.
To get the required output, use the following format string:
>>> import time
>>> time.strftime("%a %b %d %H:%M %Y", time.localtime())
'Thu Oct 11 17:23:28 2018'
Upvotes: 2