Python如何进行时间处理
我们会经常遇到对时间的处理,用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时间处理的资料请关注其它相关文章!
上一篇: Janusgrap编程指南-Schema设计高级篇v1.0
下一篇: 图片自动生成子图并添加图片水印