Home  >  Q&A  >  body text

python - Why does formatting with time.strftime use the default value?

a = time.time()

time.sleep(3)

b = time.time()

time_consuming = time.strftime("%H:%M:%S", time.localtime(b - a))
print(time_consuming)

Use the above code to run time.strftime. After formatting the time, there is always a default value for the hour. How did this 8-hour default value come about?

PHP中文网PHP中文网2711 days ago580

reply all(2)I'll reply

  • 迷茫

    迷茫2017-05-18 10:52:41

    Due to time zone issues, time should not be used, datetime.timedelta should be used to calculate
    Refer to the code below

    import time
    import datetime
    
    a = time.time()
    
    time.sleep(3)
    
    b = time.time()
    print datetime.timedelta(seconds=(b -a ))  # <-- 推荐
    time_consuming = time.strftime("%H:%M:%S", time.gmtime(b - a))  # <-- 不推荐
    print(time_consuming)

    The output is as follows:

    0:00:03.004802
    00:00:03

    reply
    0
  • 阿神

    阿神2017-05-18 10:52:41

    8 hours is caused by time zone conversion: Beijing is the East Eighth District, and the time needs to be added forward by 8 hours.

    reply
    0
  • Cancelreply