time Module

Get to know time module

Some Functions in the time Module

Function Description
asctime([tuple]) Converts time tuple to a string
localtime([secs])Converts seconds to a date tuple, local time
mktime(tuple) Converts time tuple to local time
sleep(secs) Sleeps (does nothing) for secs seconds
strptime(string[, format]) Parses a string into a time tuple
time() Current time (seconds since the epoch, UTC)

Use time structure


import time# from  ww  w .  j a  v a  2 s. c  o  m
gmt = time.gmtime(time.time())
fmt = '%a, %d %b %Y %H:%M:%S GMT'
str = time.strftime(fmt, gmt)
hdr = 'Date: ' + str
print hdr

The code above generates the following result.

time.asctime

The function time.asctime formats the current time as a string, such as


import time

print time.asctime()

The code above generates the following result.

time.time()

time.time() returns the current system time.


import time

print time.time()

The code above generates the following result.

time.localtime(secs)

time.localtime(secs) returns the time in the form of (year, month, day, hour, minute, second, day of week, day of year, daylight savings).


import time#   w ww.j  a va2s  . c  om
print time.localtime()
t = time.localtime()
print t
print t[3]
print t[4]
print t[5]

The code above generates the following result.

time.ctime(secs)

time.ctime(secs) returns the time, specified by secs since the UTC, as a formatted, printable string.


import time

print time.ctime()

The code above generates the following result.

time.clock()

time.clock() returns the current CPU time as a floating-point number that can be used for various timing functions.


import time

print time.clock()

The code above generates the following result.

mktime


from random import *
from time import *
# w ww  . j a v  a  2  s .c o  m
date1 = (2005, 1, 1, 0, 0, 0, -1, -1, -1)
time1 = mktime(date1)
date2 = (2006, 1, 1, 0, 0, 0, -1, -1, -1)
time2 = mktime(date2)
random_time = uniform(time1, time2)
print asctime(localtime(random_time))

The code above generates the following result.

time.strftime

You can print the time values using the strftime() method.


import time

print time.strftime("%I:%M")

The code above generates the following result.

time.sleep

time.sleep(sec) forces the current process to sleep for the number of seconds specified by the floating-point number secs.


import time#   ww w  . j a v a2 s  .  c o  m
for x in range(3):
    print "The time is now", time.asctime()
    print "Now sleeping for 2 seconds..."
    time.sleep(2)

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules