[Arrangement] conversion and calculation of strings and time in Python
Last Update:2018-12-06
Source: Internet
Author: User
1. conversions between string time and datetime
1. String-> time >>> Time. strptime ('2017-08-04 ',' % Y-% m-% D ')
Time. struct_time (tm_year = 2012, tm_mon = 8, tm_mday = 4, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 5, tm_yday = 217, tm_isdst =-1)
2. Time-> string >>> Import time # method 1
>>> Time. strftime ('% Y-% m-% d', time. localtime () #'2017-08-04' # method 2
>>> Time. strftime ('% Y-% m-% d', time. localtime (time. time () #'2017-08-04 'Where strftime (which should be the meaning of string format time) is used to format the time. The first parameter is the formatted string, the second parameter is a struct, and time. the time () function is used to obtain the machine time.
3. String-> datetime # Method 1 convert data by string-> time-> datetime> Import datetime
>>> Datetime. datetime (
* Time. strptime ('2017-08-04 ',' % Y-% m-% D') [: 3]) # datetime. datetime (2012, 8, 4, 0, 0) # method 2 >>> import datetime >>> datetime. datetime. strptime ('2017-08-04 ',' % Y-% m-% D') # datetime. datetime (2012, 8, 4, 0, 0)
4. datetime-> string >>> Import datetime >>> now = time. localtime () >>> dt = datetime. datetime (* now [: 3]) # returns a string in the specified format >>> DT. strftime (format = '% Y-% m-% D') #'2017-08-04' # returns a string in the default format >>> DT. ctime () # 'sat Aug 4 00:00:00 123'
5. Time-> datetime >>> Import datetime
>>> Now = time. localtime () >>> datetime. datetime (* now [: 3]) # datetime. datetime (2012, 8, 4, 0, 0)
6. datetime-> time >>> DT. timetuple ()
Output: time. struct_time (tm_year = 2012, tm_mon = 8, tm_mday = 4, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 5, tm_yday = 217, tm_isdst =-1)
Ii. datetime Calculation Addition and subtraction of datetime will involve timedelta
1. time subtraction >>> Dt1 = datetime. datetime (2012, 8, 4, 20, 33, 34)
>>> Dt2 = datetime. datetime (2012, 7, 5, 14, 22, 32)
>>> Dt1-dt2 # datetime. timedelta (30,222 62) >>> (dt1-dt2). Days #30
2. After a period of time or before >>> Dt1 + datetime. timedelta (days = 10) # datetime. datetime (2012, 8, 14, 20, 33, 34)> dt1-datetime.timedelta (days = 10) # datetime. datetime (2012, 7, 25, 20, 33, 34) >>> dt4 = datetime. date (2012, 8, 14)
>>> Dt5 = datetime. Date (2012, 7, 22)
>>> Dt4-dt5 # datetime. timedelta (23)