1 # -*- coding:utf-8 -*- 2 import pandas as pd 3 import time 4 import datetime 5 6 start_date = '2020-06-08' 7 # 一、將字符串文本類型轉化為時間 8 # %Y-%m-%d 為自定義時間格式,也可設置成完整格式:%Y-%m-%d %H:%M:%S,若使用完整格式,輸入的start_date的文本格式也要完整對應,否則報錯 9 # 1.使用datetime包 10 date_time = datetime.datetime.strptime(start_date, '%Y-%m-%d') # 轉化后的時間是帶有時分秒的 11 print(date_time) # 2020-06-08 00:00:00 12 print(type(date_time)) # <class 'datetime.datetime'> 13 """ 14 datetime模塊中主要使用的是: 15 datetime.date:日期(2020-01-01) 16 datetime.time:時間(12:00:00) 17 datetime.datetime:時期(2020-01-01 12:00:00) 18 """ 19 # 2.使用time包中的time.strptime 20 time_time = time.strptime(start_date, '%Y-%m-%d') # 返回struct_time對象。 21 print(time_time) 22 print(type(time_time)) # <class 'time.struct_time'> 23 """ 24 參數解釋:time.struct_time(tm_year=年, tm_mon=月, tm_mday=日, tm_hour=時, tm_min=分, tm_sec=秒, 25 tm_wday=星期(0-6),星期一為0, tm_yday=一年中第幾天, tm_isdst=-1是否是夏令時,1-夏令時,0-非夏令時 -1-不確定,默認是-1) 26 """ 27 28 # 3.直接使用pandas的to_datetime(文本)--主要用來處理組數據 29 pd_time = pd.to_datetime(start_date) # 轉化后的時間是帶有時分秒的 30 print(pd_time) # 2020-06-08 00:00:00 31 print(type(pd_time)) # <class 'pandas._libs.tslibs.timestamps.Timestamp'> 32 33 # 從上述時間類型中提取某個字段數據出來 ,其他字段類似.year/month/day/weekday()/isoweekday()返回的1-7代表周一--周日/。。。 34 print(date_time.month) 35 print(time_time.tm_yday) 36 print(pd_time.weekday()) 37 # 若轉化一列數據的時間類型使用:pd.to_time(文件['列名']) ,此時若提取其中數據字段:文件['列名'].dt.month/year...(ps:后面內容有涉及)
1 # 例如: 2 df = pd.read_excel('./北京天氣2018.xls') # 讀取 北京天氣2018.xls文件 3 pd.to_datetime(df['日期']) # 將日期這一列變成時間類型 4 print(df['日期'].dt.month) # 使用.dt提取日期屬性 5 6 7 # 二、將時間格式轉為字符串 8 # 1.使用str或 strftime 9 print(str(pd_time)) 10 print(type(str(pd_time))) 11 12 str_time1 = date_time.strftime('%Y-%m-%d %H:%M:%S') 13 print(str_time1) # 2020-06-08 00:00:00 14 print(type(str_time1)) 15 16 str_time2 = pd_time.strftime('%Y-%m-%d %H:%M') 17 print(str_time2) # 2020-06-08 00:00 18 print(type(str_time2)) 19 20 # 2.time包時間格式的轉換 21 str_time3 = time.strftime('%Y-%m-%d', time_time) 22 print(str_time3) # 2020-06-08 23 print(type(str_time3)) # <class 'str'>
1 # 三、時間的計算 2 import pandas as pd 3 import time 4 import datetime 5 6 # 1.簡單的時間計算 7 start_date = '2020-06-08 10:00:00' 8 end_date = '2020-06-10 15:30:00' 9 start_time = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') 10 end_time = datetime.datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S') 11 during_time = end_time - start_time 12 # during_time = pd.to_datetime(end_date) - pd.to_datetime(start_date) 13 # 這里不適宜使用time.strptime時間化,因為time.struct_time無法進行計算 14 print(during_time) # 2 days, 5:30:00 15 print(during_time.days) # 2 16 print(during_time.seconds) # 小時之間相差的秒數19800 17 print(during_time.total_seconds()) # 總共相差的秒數192600.0 18 19 # 2.timedelta時間計算 20 # timedelta --datetime模塊下的,主要是用於日期計算的,代表兩個時間之間的時間差,兩個date或datetime對象相減就可返回一個timedelta對象 21 # 在需要使用到時間間隔的時候非常有用,例如需要上一個月,前一天,上一周這樣的日期,就可以使用datetime和timedelta很容易得到。 22 # datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) 23 today = datetime.datetime.today() 24 # today = datetime.date.today() 只有年月日的日期 25 # 上個月最后一天 26 last_month_last_day = datetime.date(today.year, today.month, 1) - datetime.timedelta(1) 27 print(last_month_last_day) 28 # 上個月的第一天 29 print(datetime.date(last_month_last_day.year, last_month_last_day.month, 1)) # 2020-05-01 30 # 一周之前 31 print(today - datetime.timedelta(7)) 32 print(today - datetime.timedelta(weeks=1)) # 等價 33 # 3小時30分鍾之前--其他類似 34 print(today - datetime.timedelta(hours=3, minutes=30)) 35 print(datetime.timedelta(hours=3, seconds=22).total_seconds()) # 3小時22秒的總秒數 10822.0 36 # 8小時30秒后 37 print(today + datetime.timedelta(hours=8, seconds=30)) 38 # 本周一 39 this_monday = today - datetime.timedelta(today.isoweekday() - 1) # .isoweekday()返回的1-7代表周一--周日 40 print(this_monday) 41 # 本周二 --其他類似 42 print(today - datetime.timedelta(today.isoweekday() - 2)) 43 # 本周日 44 this_sunday = today - datetime.timedelta(today.isoweekday() - 7) 45 print(this_sunday) 46 # 上周一 47 print(this_monday-datetime.timedelta(weeks=1)) 48 print(this_monday-datetime.timedelta(7)) # 等價 49 # 上周日 50 print(this_sunday-datetime.timedelta(weeks=1)) 51 52 # 3.pandas模塊對時間的處理 53 # 有下面一數據 54 data = {'date': ['2020-05-29', '2020-05-30', '2020-05-31', '2020-06-01', '2020-06-02', '2020-06-03', '2020-06-04', 55 '2020-06-05', '2020-06-06', '2020-06-07', '2020-06-08', '2020-06-09'], 56 'lower_temp': [17, 18, 22, 22, 23, 22, 22, 21, 21, 22, 22, 24], 57 'high_temp': [25, 19, 28, 30, 33, 28, 30, 23, 28, 29, 28, 29] 58 } 59 df = pd.DataFrame(data)
1 # 3.1.根據原數據類型進行查詢 2 # 設定date為索引(即設置date列為行名),方便按日期篩選--date為字符串文本類型 3 # 下面輸入的'2020-06-01'等日期是字符串文本類型,因此索引的類型也要字符串文本類型,否則無法匹配尋找 4 # date若為時間類型可先進行轉換文本:df['date'] = df['date'].dt.strftime('%Y-%m-%d') 5 df.set_index('date', inplace=True)6 # (1)使用單個日期 7 print(df.loc['2020-06-01', :]) # :表示是所有列 8 print(df.loc['2020-06-01', 'high_temp']) 9 print(df.loc['2020-06-01', 'lower_temp':'high_temp']) # 'lower_temp'至'high_temp'列 10 # (2)使用多個日期 11 print(df.loc[['2020-06-01', '2020-06-05'], 'high_temp']) # 6-1,6-5的高溫high_temp 12 print(df.loc['2020-06-01':'2020-06-05', 'high_temp']) # 6-1至6-5的高溫high_temp 13 14 # 3.2.轉化為時間類型進行查詢 15 # (1)對date時間這一列轉為時間格式 16 df['date'] = pd.to_datetime(df['date']) 17 # (2)篩選某個時間片段 18 print(df.loc[df['date'] == pd.to_datetime('2020-06-03')]) # 6.3的數據 19 print(df.loc[df['date'] >= pd.to_datetime('2020-06-03')]) # 6.3之后的數據 20 # 篩選滿足多個條件的數據--條件之間用&連接 21 print(df.loc[(df['date'] >= pd.to_datetime('2020-06-03')) & (df['date'] <= pd.to_datetime('2020-06-05'))]) # 6.3-6.5數據 22 print(df.loc[(df['date'] >= pd.to_datetime('2020-06-01')) & (df['high_temp'] >= 30)]) 23 24 """ 25 # 若是設置date時間格式列為索引,上述代碼要改寫 26 df.set_index('date', inplace=True) 27 print(df.loc[pd.to_datetime('2020-06-03')]) 28 print(df.loc[:pd.to_datetime('2020-06-03'), :]) # 6.3之前的數據 29 print(df.loc[pd.to_datetime('2020-06-03'):, :]) # 6.3之后的數據 30 print(df.loc[pd.to_datetime('2020-06-03'):pd.to_datetime('2020-06-05'), :]) # 6.3-6.5數據 31 """ 32 # (3)判斷某個日期是周幾、出現的次數等等。。。 33 print(df['date'].dt.weekday) # 直接顯示date這一列的星期數0-6周一-周日 34 print(df['date'].dt.is_month_start) # 判斷是否是一個月的開始 35 print(df['date'].dt.is_month_end) # 判斷是否是一個月的結束 36 print(df['date'].dt.is_leap_year) # 判斷是否閏年 37 print(df['date'].dt.year.value_counts()) # 判斷年出現的次數 38 print(df['date'].dt.month.value_counts()) # 判斷月出現的次數 39 40 # (4對日期增減 41 import dateutil # 導入新庫 42 # 增加1天(減少天用-號) 43 print(pd.to_datetime('2020-06-03')+dateutil.relativedelta.relativedelta(days=1)) # 2020-06-04 00:00:00 44 # 增加2年 45 print(pd.to_datetime('2020-06-03')+dateutil.relativedelta.relativedelta(years=2)) # 2022-06-03 00:00:00 46 # 對月/時/分/秒增加直接將變量名改為months/hours/minutes/seconds 即可 47 print(pd.to_datetime('2020-06-03')+dateutil.relativedelta.relativedelta(years=2, days=50, minutes=10)) # 2022-07-23 00:10:00 48 # 若將參數變成單數year/day/month/hour/minute/second 並不是日期的加減,而是將日期對應值變成所設置的參數值 49 print(pd.to_datetime('2020-06-03')+dateutil.relativedelta.relativedelta(year=1991, day=5, minute=10)) # 1991-06-05 00:10:00