我们会经常遇到对时间的处理,用python来进行时间处理简直不要太方便了,这一期就给大家介绍一下python的时间处理!
用python进行时间处理主要会用到time,calendar,datetime及pandas这几个库,其中又以后两个最为常用。
这一期我们主要介绍一下用datetime库进行时间处理的常用操作。
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. 时间格式的转换
- strftime 即 string format time,用来将时间格式化成字符串
- strptime 即 string parse time,用来将字符串解析成时间
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'
这一期主要介绍了是datetime进行时间处理的一些常用操作,后续我们会介绍pandas中的一些时间处理的操作。欢迎点赞转发期待哦~
以上就是Python如何进行时间处理的详细内容,更多关于Python时间处理的资料请关注其它相关文章!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!