Detailed description of the use of the time module in Python Programming

Source: Internet
Author: User
Tags julian day month name
This article mainly introduces how to use the time module in Python programming. It is the basic knowledge of getting started with Python. For more information, see I. Introduction

The time module provides functions for various operation times.
Note: There are two methods to indicate time:
The first method is the timestamp (offset calculated in seconds relative to 00:00:00). The timestamp is unique.
The second type is represented as an array (struct_time). There are nine elements, respectively, indicating that the struct_time of the same timestamp varies with the time zone.

  • Year (four digits, e.g. 1998)
  • Month (1-12)
  • Day (1-31)
  • Hours (0-23)
  • Minutes (0-59)
  • Seconds (0-59)
  • Weekday (0-6, Monday is 0)
  • Julian day (day in the year, 1-366)
  • Whether DST (Daylight Savings Time) flag (-1, 0 or 1) Is Daylight Saving Time
  • If the DST flag is 0, the time is given in the regular time zone;
  • If it is 1, the time is given in the DST time zone;
  • If it is-1, mktime () shoshould guess based on the date and time.

License Introduction: http://baike.baidu.com/view/100246.htm

UTC Introduction: http://wenda.tianya.cn/wenda/thread? Tid = 283921a9da7c5aef & clk = wttpcts

Ii. Function Introduction

1. asctime ()

Asctime ([tuple])-> string

Converts a struct_time (default time) to a string.
Convert a time tuple to a string, e.g. 'sat Jun 06 16:26:11 123 '.
When the time tuple is not present, current time as returned by localtime () is used.

2. clock ()

Clock ()-> floating point number
This function has two functions,
During the first call, the actual running time is returned;
After the second call, the returned time interval from the first call to the current call is

Note:
Use time. time () on Xinux and use time. clock () in windows to get higher precision.
Xinux and Win have different clock implementations. Time. clock () is the implementation of the called system clock, and the two platforms are different.
The main problem lies in the Xinux clock switching policy: jiffy implementation, because the kernel clock switching is not continuous but interval for a period of time (generally 1 ms ~ It only changes after 10 ms. Therefore, if it is two short-lived calls in Xinux, the results will be the same through time. clock.

3. sleep (...)

Sleep (seconds)
The thread delays running at a specified time. It has been tested and measured in seconds.
Example:

import time if __name__ == '__main__':   time.sleep(3)   print "clock1: %s" % time.clock()   # print "local time: %s" % time.localtime()   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))   time.sleep(3)   print "clock2: %s" % time.clock()   # print "local time: %s" % time.localtime()   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))   time.sleep(3)   print "clock3: %s" % time.clock()   # print "local time: %s" % time.localtime()   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

Result

clock1: 0.0206782015-08-09 00:18:31clock2: 0.0208912015-08-09 00:18:34clock3: 0.0210682015-08-09 00:18:37

4. ctime (...)

Ctime (seconds)-> string
Converts a timestamp (current time by default) into a time string.
For example:

time.ctime()

Output:

'Sat Mar 28 22:24:24 2009′

5. gmtime (...)

Gmtime ([seconds])-> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
Converts a timestamp to struct_time of UTC time zone (0 Time Zone). If the seconds parameter is not input, the current time is used as the conversion standard.

6. localtime (...)

Localtime ([seconds])-> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
Converts a timestamp to struct_time of the current time zone. If the seconds parameter is not input, the current time is used as the conversion standard.

7. mktime (...)

Mktime (tuple)-> floating point number
Converts a struct_time to a timestamp.

8. strftime (...)

Strftime (format [, tuple])-> string
Returns the specified struct_time (current time by default) according to the specified formatted string.
Time and date formatting symbols in python:

  • % Y two-digit year (00-99)
  • % Y indicates the four-digit year (000-9999)
  • % M month (01-12)
  • One day in % d month (0-31)
  • % H hour in 24-hour format (0-23)
  • % I 12-hour (01-12)
  • % M minutes (00 = 59)
  • % S seconds (00-59)
  • % A local simplified week name
  • % A local full week name
  • % B local simplified month name
  • % B local full month name
  • % C local Date and Time
  • % J one day in the year (001-366)
  • % P local equivalent of A. M. or P. M.
  • % U number of weeks in a year (00-53) Sunday is the start of the week
  • % W Week (0-6), Sunday is the beginning of the week
  • % W number of weeks in a year (00-53) Monday is the start of the week
  • % X local date Representation
  • % X Local Time Representation
  • % Z Current Time Zone name
  • % Itself

print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

 2015-08-09 00:18:37

9. strptime (...)

Strptime (string, format)-> struct_time
Converts a time string to a time string in the array format based on the specified formatting character.
For example:
The format string for 11:45:39 is: % Y-% m-% d % H: % M: % S
Sat Mar 28 22:24:24 2009 formatted string: % a % B % d % H: % M: % S % Y

10. time (...)

Time ()-> floating point number
Returns the timestamp of the current time (the number of floating point seconds after the 1970 EPOCH)

Iii. Common commands

1. Obtain the current time using python

Time. time () Get the current Timestamp
Time. localtime () struct_time form of the current time
Time. ctime () string format of the current time

print time.time() print time.localtime() print time.ctime()

Result:

1439051479.08time.struct_time(tm_year=2015, tm_mon=8, tm_mday=9, tm_hour=0, tm_min=31, tm_sec=19, tm_wday=6, tm_yday=221, tm_isdst=0) Sun Aug 9 00:31:19 2015

2. format strings in python

Formatted as 11:45:39

time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime())

Formatted as Sat Mar 28 22:24:24 2009

time.strftime(“%a %b %d %H:%M:%S %Y”, time.localtime())

3. Convert the format string to the timestamp

A = "Sat Mar 28 22:24:24 2009 ″

b = time.mktime(time.strptime(a,”%a %b %d %H:%M:%S %Y”))

Ps:
To understand this section, we mainly want to use time to calculate the key and non-running time in our program. Therefore, we need to organize this part more. As for the time conversion, we will sort it out later when necessary.

4. Use the time module to calculate the Accuracy Test of code execution efficiency

# Using the time module in python to calculate code execution efficiency # using time for testing. time () and time. clock () uses the precision import sys import time import timeit default_timer = None if sys. platform = "win32": # On Windows, the best timer is time. clock () default_timer = time. clock else: # On most other platforms the best timer is time. time () default_timer = time. time print default_timer timeIn = time. clock () for I in range (100): n = I timeUse = time. clock ()-timeIn p Rint timeUse timeIn = time. time () for I in range (100): n = I timeUse = time. time ()-timeIn print timeUse timeIn = timeit. default_timer () for I in range (100): n = I timeUse = timeit. default_timer ()-timeIn print timeUse # The result of this section of code in windows is as follows> 4.07873067161e-005 0.0 3.5758734839e-005 # because of time. clock () returns the processor time, and the accuracy is not too high because of jiffy in Unix. # Therefore, in Windows, time is recommended. clock () is recommended in Unix systems. time (), # Use timeit instead of time to achieve cross-platform precision, using timeit. default_timer () function to obtain the time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.