您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python進行時間處理的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
1. datetime基礎
1.1 獲取當前時間
import time import datetime as dtm ## 用datetime獲取當前時間 dtime = dtm.datetime.now() # dtm.datetime.utcnow() dtime # datetime.datetime(2018, 12, 15, 13, 1, 30, 200649) # 年、月、日、時、分、秒、微秒 dtime.year, dtime.month, dtime.day # (2018, 12, 15) dtm.datetime.strftime(dtm.datetime.now(), '%Y-%m-%d %H:%M:%S') # '2018-12-15 20:47:45' # 用time庫獲取當前時間: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time( ))) # '2018-12-15 20:49:17' time.strftime("%Y-%m-%d %H:%M:%S") # '2018-12-15 20:50:11'
1.2 datetime基本操作
from datetime import datetime, date, time # Using datetime.combine() d = date(2005, 7, 14) t = time(12, 30) datetime.combine(d, t) datetime(2005, 7, 14, 12, 30) # datetime 類的方法: datetime.date() datetime.time() # 可以用str()直接將時間格式轉化為字符串 dt = datetime(2005, 7, 14, 12, 30) # datetime(%Y,%m,%d,%H,%M,%S): # datetime共有6個參數,分別代表的是年月日時分秒。其中年月日是必須要傳入的參數,時分秒可以不傳入,默認全為零。 # >>> # Using datetime.timetuple() to get tuple of all attributes tt = dt.timetuple() for it in tt: print(it) # 2005 # year # 7 # month # 14 # day # 12 # hour # 30 # minute # 0 # second # 3 # weekday (0 = Monday, 6 = Sunday) # 195 # number of days since 1st January # -1 # dst - method tzinfo.dst() returned None #################################################### # 返回今天是周幾 x='2018-05-27' int(dtm.datetime(int(x[ :4]),int(x[5:7]),int(x[8: ])).strftime('%w')) # 0 表示周日 dtm.datetime(2017, 1, 1).strftime("%w") # 0-6 SUN-SAT
2. 時間戳的轉換
Unix時間戳: Unix 中常常使用一個數字記錄時間,表示距離起始時間相差的秒數(根據系統的精度,時間單位有時毫秒,有時是納秒)。大于 0 表示在起始時間之后,小于 0 就表示在起始時間之前。這個數字有時是浮點類型、有時是整數類型,但都稱這個數字為 Unix 時間戳(Timestamp)
import time import datetime as dtm ## 獲取當前時間 dtime = dtm.datetime.now() # dtm.datetime.utcnow() # 時間戳 ans_time = int(time.mktime(dtime.timetuple())) ans_time # 1535860540 # 時間戳的轉換-1 t1 = datetime.datetime.fromtimestamp(ans_time) # local time t1 # datetime.datetime(2018, 9, 2, 11, 55, 40) # 也可以用time模塊的localtime()方法: time.localtime(ans_time) # 時間戳的轉換-2 t2 = datetime.datetime.utcfromtimestamp(ans_time) # utc time t2 # datetime.datetime(2018, 9, 2, 3, 55, 40) t2.strftime("%Y--%m--%d %H:%M:%S") # 2018--09--02 03:55:40 # 時間戳的轉換-3 pd.to_datetime(ans_time,unit='s') # utc time # Timestamp('2018-09-02 03:55:40')
3. 時間格式的轉換
import datetime as dtm start = dtm.datetime(2011,1,7,1,21,1) # datetime.datetime(2011, 1, 7, 1, 21, 1) start.strftime('%Y-%m-%d %H:%M:%S') # '2011-01-07 01:21:01' dtm.datetime.strptime('2011-01-07 01:21:01','%Y-%m-%d %H:%M:%S') # datetime.datetime(2011, 1, 7, 1, 21, 1) str(start) # '2011-01-07 01:21:01' start.strftime("%Y-%m-%d 00:00:00") # '2011-01-07 00:00:00' # The strftime method formats a datetime as a string: In [1]: dt.strftime('%m/%d/%Y %H:%M') Out[1]: '10/29/2011 20:30' # Strings can be converted (parsed) into datetime objects using the strptime function: In [2]: dtm.datetime.strptime('20091031', '%Y%m%d') Out[2]: datetime.datetime(2009, 10, 31, 0, 0) >>> z dtm.datetime(2012, 9, 23, 21, 37, 4, 177393) >>> nice_z = dtm.datetime.strftime(z, '%A %B %d, %Y') >>> nice_z 'Sunday September 23, 2012' # 字符串形式的時間格式轉化為時間格式 dt = dtm.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") # 時間格式轉化為字符串 # time.strftime( '%Y-%m-%d' , time.localtime(time.time())) # >>> # Formatting datetime print(dt.strftime("%A, %d. %B %Y %I:%M%p")) # 'Tuesday, 21. November 2006 04:30PM' 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time") # 'The day is 21, the month is November, the time is 04:30PM.' ''' Datetime format specification: %Y Four-digit year %y Two-digit year %m Two-digit month [01, 12] %d Two-digit day [01, 31] %H Hour (24-hour clock) [00, 23] %I Hour (12-hour clock) [01, 12] %M Two-digit minute [00, 59] %S Second [00, 61] (seconds 60, 61 account for leap seconds) %w Weekday as integer [0 (Sunday), 6]
datetime.strptime解析時間需要輸入相應的時間格式,而dateutil第三方庫中的parser.parse方法則更加靈活。
dateutil.parser 有時候也會有一定的麻煩,比如 '42'會被解析為2042 年加上今天的日期:datetime.datetime(2042, 9, 1, 0, 0)
from dateutil.parser import parse parse('2011-01-03') # datetime.datetime(2011, 1, 3, 0, 0) parse('Jan 31, 1997 10:45 PM') # datetime.datetime(1997, 1, 31, 22, 45) parse('6/12/2011', dayfirst=True) # datetime.datetime(2011, 12, 6, 0, 0) # pandas: datestrs = ['2011-07-06 12:00:00', '2011-08-06 00:00:00'] pd.to_datetime(datestrs) # DatetimeIndex(['2011-07-06 12:00:00', '2011-08-06 00:00:00'], dtype='datetime64[ns]', freq=None)
4. Timedelta
timedelta 可以表示兩個時間之間的時間差:
dtm.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
t1 = dtm.datetime(2018,7,12,15,6,9) t2 = dtm.datetime(2018,9,11,12,33,23) td = t2-t1 td # datetime.timedelta(60, 77234) td.days,td.seconds # (60, 77234) # 將timedelta轉換為: day, hour, minute def parse_timedelta(td): """ transform timedelta to day, hour, minute """ return td.days, td.seconds//3600, (td.seconds//60)%60 parse_timedelta(td) # (60, 21, 27)
利用timedelta進行時間外推:
import datetime as dtm # 100天前的日期 (dtm.datetime.now() - dtm.timedelta(days = 100)).strftime("%Y-%m-%d") def TaftD(FORMAT_DATE,i): """ 返回幾天后的時間 """ return (dtm.datetime.strptime(FORMAT_DATE, '%Y-%m-%d') + dtm.timedelta(days = i)).strftime('%Y-%m-%d') def TaftH(FORMAT_TIME,i): """ 返回幾小時后的時間 """ return (dtm.datetime.strptime(FORMAT_TIME, '%Y-%m-%d %H:%M:%S') + dtm.timedelta(hours = i)).strftime('%Y-%m-%d %H:%M:%S') TaftD("2018-05-17", -2) # '2018-05-15' TaftH("2018-05-17 10:40:00", 2) # '2018-05-17 12:40:00'
感謝你能夠認真閱讀完這篇文章,希望小編分享Python進行時間處理的方法內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。