One, Time module
Let's start by introducing some of the time-representation methods you'll use.
(1) Timestamp: Refers to how many seconds have elapsed since the beginning of the Unix period, such as the first article of the result;
(2) Time tuple: In the last 2 lines of the command, the output is the time tuple format.
(3) Self-formatted time, that is, the second run results, you can define the time display format.
It is commonly used as follows:
Time stamps and well-formatted time are converted to each other, requiring a bridge, which is the time tuple.
Example 1: Converting a timestamp to a formatted time, shown in the format: year-month-day time: minutes: seconds.
Analysis: The first step should be to convert the timestamp into a time tuple, i.e. use Time.localtime (). The second step is to convert the time tuple into a well-formatted time, that is, using Time.strftime ()
Import TimedefTimestamp_to_format (timestamp = None,format ='%y-%m-%d%h:%m:%s'): #1, the default return to the current format good time #2, to the time stamp, the time stamp into a format good time, return ifTimestamp:time_tuple=time.localtime (timestamp) Res=time.strftime (format,time_tuple)Else: Res= time.strftime (format)#default fetch Current time returnResresult=Timestamp_to_format ()Print(Result)
Example 2: Convert a formatted time into a timestamp.
Analysis: First convert the formatted time into a time tuple, and then convert the time tuple into a timestamp.
Import TimedefStrtotimestamp (str=none,format='%y%m%d%h%m%s'): ifStr:#If you pass the time,TP = Time.strptime (Str,format)#format a good time, turn it into a time tupleres = TIME.MKTIME (TP)#and turn it into a timestamp . Else: Res= Time.time ()#default Fetch current timestamp returnInt (res) result= Strtotimestamp (str='2018-5-3 19:47:32', format='%y-%m-%d%h:%m:%s')Print(Result)
Second, the DateTime module
Among them, Datetime.timedelta () is optionally available in parentheses with weeks,days,minutes,seconds, such as:
python-Time Module