zjm1126
zjm1126

Reputation: 35670

How can I get the seconds of the time in Python?

This is my code:

last_time = get_last_time()
now = time.time() - last_time
minute = 
seconds = 
print 'Next time you add blood is '+minute+':'+seconds

Because recovery blood every 5 minutes so only need minute and second.

Upvotes: 24

Views: 136944

Answers (3)

user2665694
user2665694

Reputation:

This is basic time arithmetics...if you know that a minute has 60 seconds then you could have found that yourself:

minute = now // 60
seconds = now % 60

Or if you want integers (discarding fractional seconds),

minute = int(now // 60)
seconds = int(now % 60)

Upvotes: 22

quywter
quywter

Reputation: 67

In Python 3,

>>import time
>>time.localtime()
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=16, tm_hour=1, tm_min=51, tm_sec=39, tm_wday=0, tm_yday=197, tm_isdst=0)

You can scrape the minutes and seconds like that,

>>time.localtime().tm_min
51
>>time.localtime().tm_sec
39

I think, this can solve your problem.

Upvotes: 4

Zecc
Zecc

Reputation: 4340

I believe the difference between two time objects returns a timedelta object. This object has a .total_seconds() method. You'll need to factor these into minutes+seconds yourself:

minutes = total_secs % 60
seconds = total_secs - (minutes * 60)

When you don't know what to do with a value in Python, you can always try it in an interactive Python session. Use dir(obj) to see all of any object's attributes and methods, help(obj) to see its documentation.

Update: I just checked and time.time() doesn't return a time object, but a floating point representing seconds since Epoch. What I said still applies, but you get the value of total_secs in a different way:

total_secs = round(time.time() - last_time)

So in short:

last_time = get_last_time()
time_diff = round(time.time() - last_time)
minute = time_diff / 60
seconds = time_diff % 60  # Same as time_diff - (minutes * 60)
print 'Next time you add blood is '+minute+':'+seconds

Upvotes: 8

Related Questions