basically deals with time types every day in daily work, such as the creation time of each piece of data in database , and the update time that needs to be written when updating. So the question is as follows:
Does it want UTC Time (world unified time) or local time? How to format the format of
date?
If I get a timestamp, how should I convert it to the target time?
What should I do if I want to convert the time of the database into a timestamp?
, etc.

, what is said above is not complicated, but you must know that if even such basics need to be retrieved when used, then there is no need to talk about efficiency.
, let’s take a look at using the datetime library to manage and convert dates and time through several examples.
Example 1: Get the current time
import time
from datetime import datetime
now = datetime.now()
print(f'Current time: {now}')
print(f'Current time split: {now.year, now.month, now.day}')
strf_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
print(f'format current time: {strf_now}')
strf_now_1 = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
print(f'format current time-1: {strf_now_1}')
OUTPUT
Current time: datetime.datetime(2020, 12, 13, 16, 5, 57, 448449)
Current time split: (2020, 12, 13)
Format the current time: '2020-12-13 16:05:57.448602'
Format the current time-1: '2020-12-13 16:05:57'
Explain the above code: datetime.now() in
now is used to obtain the current time, and the returned data is datetime type; .year .mongo .day Used to obtain year, month and day respectively; strftime in
strf_now is used to format data of datetime type; after formatting, the data of strftime is returned; another method of formatting using strftime is demonstrated in
strf_now_1. The returned result and data type are the same as strf_now. Here, I will write the two methods mentioned above in pseudo-code
{datetime type object}.strftime( {format group} )
datetime.strftime( {datetime type object}, {format group} )
strftime The format characters of the text have been sorted out at the end of the article and can be saved and can be easily read when used.
Example 2: Get the current UTC time
from datetime import timedelta
utc_now = datetime.utcnow()
print(f'UTC Current time: {utc_now}')
utc2local = utc_now + timedelta(hours=8)
print(f'local current time: {utc2local}')
OUTPUT
UTC Current time: datetime.datetime(2021, 9, 8, 12, 13, 31, 472850)
Local current time: datetime.datetime(2021, 9, 8, 20, 13, 31, 472850)
Explain the above code:
datetime.utcnow() is used to obtain UTC (global unified) time, and the returned data type is datetime Type;
utc2local completes the process of UTC time to the current time (Popular Science: UTC time to the current time is actually just adding 8 hours on the original time);
timedelta will be explained in "Instance 3", and its function is to increase or decrease a certain time based on the current time.

Instance 3: Get the time before or after a time, using timedelta can easily implement
from datetime import timedelta
delta_now = datetime.now() + timedelta(days=1)
print(f'delta_now: {delta_now}')
OUTPUT
delta_now: datetime.datetime(2021, 9, 8, 20, 54, 45, 479097)
Explain the above code:
First of all, you need to note that if you add to timedelta, you must be datetime type;
timedelta(days=1) returns the datetime type, and after addition, you will also return the datetime type;
delta_now means that on the current basis, add one day to return;
timedelta There are also many parameters supported, as follows. If multiple passes in, please pay attention to the order datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)
timedelta The value of timedelta supports negative numbers, such as days=-1, indicating that one day is subtracted.

Example 4: String time to timestamp
import time
def time2stamp(t):
time_array = time.strptime(t, '%Y-%m-%d %H:%M:%S')
print(type(time_array), '-', time_array)
timestamp = time.mktime(time_array)
return timestamp
if __name__ == '__main__':
print('-', time2stamp('2020-12-10 23:34:30'))
OUTPUT
class 'time.struct_time' - time.struct_time(tm_year=2020, tm_mon=12, tm_mday=10, tm_hour=23, tm_min=34, tm_sec=30, tm_wday=3, tm_yday=345, tm_isdst=-1)
- 1607614470.0
Explain the above code:
time.strptime() function parses a time string into a time tuple according to the specified format for subsequent use;
time.mktime() receives the structured time object as a parameter (the return value of time.strptime() above), and returns a floating point number that uses seconds to represent time;
instance 5: Current time to timestamp
import time
form datetime import datetime
def get_now_stamp():
now_time = datetime.now()
return time.mktime(now_time.timetuple())
if __name__ == '__main__':
print('-', get_now_stamp())
OUTPUT
- 1607848078.0
Instance 5 Without further ado, Example 4 has figured it out, and understanding Example 5 is naturally no problem.
Example 6: Timestamp to time
from datetime import datetime
def stamp2time(timestamp):
return datetime.fromtimestamp(timestamp)
if __name__ == '__main__':
print('-', stamp2time(1607614470))
OUTPUTh
- datetime.datetime(2020, 12, 10, 23, 34, 30)
Explanation of the above code:
datetime.fromtimestamp() Time stamp (int type) is converted to datetime type time;
or above method, it is recommended that you encapsulate it into a tool class according to your needs, including examples 4, 5, 6 It is a packaged ready-made method that can be used directly; this way it can be called easily when used;
Of course, the tool class can add many commonly used functions to it. With this weapon, your development efficiency will gradually increase.
The following is the strftime format symbol, please accept it.

**The benefits at the end of the article - recommend a "Python Automation Test Learning Exchange Group" to everyone:
Please follow + private message reply: "Toutiao" can get software test learning materials for free, and enter the group to learn and communicate~~
