[Two] common module common module (a)) time module

 

Time Module

time module

And time has a relationship we will use the time module. Before using the module, you should first import this module.

 

# Common method 
1 .time.sleep (secs) 
(thread) to postpone a specified time to run. Seconds. 
2 .time.time () 
to get the current timestamp

- indicates the time of three ways

In Python, there are typically three ways to represent time: time stamp tuples (struct_time), the formatted time string:

(1) timestamp (timestamp): Generally speaking, the timestamp indicates that from January 1970 00:00:00 1st offset press in seconds. We run "type (time.time ())", returns a float.

(2) the formatted time string (Format String): '1999-12-06'

(3) Character Meaning

% y represents a two-digit year (00-99 ) %
 the Y represents a four-digit year (000-9999 ) %
 m (01-12 )
within% d month of day (0-31 of ) %
 H 24 hours number (manufactured by 0-23 hours ) %
 h 12 is the number of the I (manufactured by 01-12 hours ) %
 M number of minutes (00 = 59 ) %
 S seconds (00-59 )
 % A simplified week local name
 % A full week of local name
 % b local simplified month name
 % B full month name local
 % C indicates the corresponding local date and time indicates
 one day (001-366% j years )
 % P AM or PM local character equivalent
 % of U week of the year number (00-53 ) on Sunday as the start of the week
 % w week (0-6 ), Sunday to begin the week of
 % W week number of the year (00-53 ) Monday to start the week of
 % the X-local corresponding date It represents
 % X-indicates the corresponding local time
% Name Z current time zone
 number %%% itself

 

(4) tuple (struct_time): struct_time tuple total of nine elements were nine elements :( year, month, day, hour, minute, second, the first few weeks of the year, day of the year, etc.)

 

  

First, we import the time module, to understand what python represents time in several formats:

# Import time module 
>>> Import Time 

# timestamp 
>>> the time.time () 
1,500,875,844.800804 

# Time String 
>>> The time.strftime ( "%% Y-X-M-% D%") 
'2017-07- 13:54:37 24 ' 
>>> The time.strftime ( "% D%% Y-H-M-%%% M-S") 
' 2017-07-24 13-55-04 ' 

# time tuples: localtime will convert a timestamp of the current time zone struct_time 
time.localtime () 
a time.struct_time (tm_year = 2017, = tm_mon. 7, 24 = tm_mday, 
          tm_hour = 13 is, tm_min = 59, = 37 [tm_sec, 
                 tm_wday = 0, = tm_yday 205, tm_isdst = 0)

  

Summary: The computer is able to identify the timestamp of the time; time string is one can read time; tuple is used to operate the time

Conversion between several formats

 

 

# Timestamp -> Structured time 
# time.gmtime (timestamp) #UTC time, consistent with the local time in London 
# time.localtime (time stamp) # local time. For example, we now perform in Beijing this method: 8 hours difference with UTC, UTC time is GMT +8 hours = 
>>> time.gmtime (1.5 billion) 
a time.struct_time (tm_year = 2017, tm_mon = 7, tm_mday = 14, tm_hour 2 =, = tm_min 40, tm_sec = 0, = tm_wday. 4, tm_yday = 195, the tm_isdst = 0) 
>>> time.localtime (1.5 billion) 
a time.struct_time (tm_year = 2017, = tm_mon. 7, tm_mday = 14, = tm_hour 10, tm_min = 40, tm_sec = 0, = tm_wday. 4, tm_yday = 195, the tm_isdst = 0) 

# structured time -> timestamp 
# time.mktime (structured time) 
>>> time_tuple = time.localtime (1.5 billion ) 
>>> time.mktime (time_tuple) 
1500000000.0

  

Structured Time # -> Time String 
# The time.strftime ( "Format Definition", "structured Time") if the structured transmission time parameter, the current time is displayed 
>>> time.strftime ( "% Y-% % D% X-M- ") 
'2017-07-24 14:55:36' 
>>> The time.strftime ("% Y-M-% D% ", time.localtime (1.5 billion)) 
'2017-07- 14 ' 

# string time -> structured time 
# the time.strptime (time string, the corresponding string format) 
>>> the time.strptime ( "2017-03-16", "% D% Y-M-% ") 
a time.struct_time (tm_year = 2017, = tm_mon. 3, tm_mday = 16, tm_hour = 0, 0 = tm_min, tm_sec = 0, = tm_wday. 3, tm_yday = 75, the tm_isdst = -1) 
>>> the time.strptime ( "07/24/2017", "% m /% D /% the Y") 
a time.struct_time (tm_year = 2017, = tm_mon. 7, 24 = tm_mday, tm_hour = 0, 0 = tm_min, tm_sec = 0, 0 = tm_wday , tm_yday = 205, tm_isdst = -1 )

 

 

 

Structured Time # ->% a% b% d % H:% M:% S% Y string 
# that time.asctime (Structured time) if the parameter does not pass directly returns the current time format string 
>>> time .asctime (time.localtime (1.5 billion)) 
'Fri Jul-14 10:40:00 2017' 
>>> that time.asctime () 
'Mon Jul-24 15:18:33 2017' 

# timestamp ->% a% b % d% H:% M: % S% Y string 
# time.ctime (timestamp) if the parameter does not pass directly returns the current time format string 
>>> time.ctime () 
'Mon Jul-24 15:19: 2017 07 ' 
>>> time.ctime (1.5 billion) 
' Fri Jul-14 10:40:00 2017 '

 

- Exercise

1 import time
2 true_time=time.mktime(time.strptime('2017-09-11 08:30:00','%Y-%m-%d %H:%M:%S'))
3 time_now=time.mktime(time.strptime('2017-09-12 11:00:00','%Y-%m-%d %H:%M:%S'))
4 dif_time=time_now-true_time
5 struct_time=time.gmtime(dif_time)
6 print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
7                                        struct_time.tm_mday-1,struct_time.tm_hour,
8                                        struct_time.tm_min,struct_time.tm_sec))
Calculate the time difference

 

 collections module

Method One: from collections import Counter

Counter object class is used to track the number of value occurs. It is an unordered type of container, in the form of key-value pairs stored in the dictionary, where the elements as key, as its count value. Count value may be any Interger (including 0 and negative numbers). Counter class and other languages ​​bags or multisets very similar.

Counter = C ( 'abcdeabcdabcaba') 
Print C 
Output: Counter ({ 'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Method two: from collections import namedtuple

Named tuples

I know that tuplecan represent the same collection, for example, two-dimensional coordinates of a point can be expressed as:

>>> p = (1, 2)

However, see (1, 2), it is difficult to see this tuple is used to represent a coordinate.

At this time, namedtupleit came in handy:

a = nametuple('alex',['x','y'])
p = alex(1,2)
p.x
p.y
2

Class similar, if use a circle represents coordinates and the radius, it can also be used namedtupledefinitions:  

#namedtuple('名称', [属性list]):
Circle = namedtuple('Circle', ['x', 'y', 'r'])

方法三:from collections import defaultdict

The default dictionary

la = [( 'red', 1), ( 'yellow', 1), ( 'green', 1), ( 'blue', 1), ( 'red', 5), ( 'green', 1 ), ( 'green', 1), ( 'green', 1)] is calculated for each color number, the format ---- { 'red': 6, 'yellow': 1, 'green': 4 'blue color ': 1}

la = [( 'red', 1), ( 'yellow', 1), ( 'green', 1), ( 'blue', 1), ( 'red', 5), ( 'green', 1 ), ( 'green', 1), ( 'green', 1)] 
P = a defaultdict (List) # { 'Key': []} 
for I in La: 
    P [I [0].] the append (I [ 1]) 
for J in dict (P): 
    P [J] = SUM (P [J]) 
Print (dict (P)) 
{ 'red': 6, 'yellow': 1, 'green': 4 ' blue ': 1}

Li = [
    { 'name': 'Alex', 'Hobby': 'smoke'},
    { 'name': 'Alex', 'Hobby': 'drink'},
    { 'name': 'Alex', 'Hobby ':' hot head '},
    {' name ':' Alex "," Hobby ":" tease sister '},
    {' name ':' wusir ',' Hobby ':' small sword '},
    {' name ' : 'wusir', 'hobby' : ' swim'},
    { 'name': 'wusir', 'hobby' : ' cards'},
    { 'name': 'Bai', 'hobby': 'hot head'} ,
    { 'name': 'Bai', 'hobby': 'feet'},
    { 'name': 'Bai', 'hobby': 'car'}
]

Print out the following format: { 'alex': [ 'smoke', 'drink', 'hot head', 'stitch sister'], 'wusir': [ 'small sword', 'swim', 'cards'],' Bai ': [' hot head ',' feet ',' car ']}

1 j = defaultdict(list)  # {'dict':[]}
2 for i in li:
3     if j.get(i['name']):
4         j[i['name']].append(i['hobby'])
5     else:
6         j[i['name']] = [i['hobby']]
7 print(dict(j))
View Code

Method four: from collections import deque

When using the list of data storage, access the elements by index quickly, but inserting and removing elements is very slow, because the list is linear memory, when a large amount of data, efficiency is very low insertion and deletion.

deque is to achieve efficient insertion and deletion of two-way list, queue and stack suitable for:

>>> from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.append('x')
>>> q.appendleft('y')
>>> q
deque(['y', 'a', 'b', 'c', 'x'])
View Code

D eque addition to achieving the list append()and pop(), also support appendleft()and popleft()so can be very efficiently add or delete elements to the head.

datetime, delta h

from datetime Import datetime, timedelta 

Print (DateTime.Now ())                               # -time objects 

F = datetime.timestamp (DateTime.Now ())    # the time of the object into a timestamp 
Print (F)
 Print (datetime.fromtimestamp (F))               # converted into time stamp objects 

Print (datetime.strptime ( ' 2018-11-30 ' , ' % Y-M-% D% ' ))    # string converted to time the object 

F = DateTime.Now ()
 Print (datetime.strftime (F, ' % Y-M-% D% ' ))   # The object into a string of time 

Print (DateTime.Now () - timedelta (= weeks. 1))   # key referred *************** 
# Parameters: seconds (sec) microseconds ( microseconds) milliseconds (ms) minutes (min) hours (h) weeks (weeks)
View Code

 

  

 

1

Guess you like

Origin www.cnblogs.com/jiazeng/p/11593326.html