Pandas之时间操作

1、常用时间

类别解释
year
month
day
hour
minute分钟
second
microsecond微秒
nanosecond纳秒
date返回日期
time返回时间
dayofyear年序日
weekofyear年序周
week
dayofweek周中的第几天,Monday=0, Sunday=6
weekday周中的第几天,Monday=0, Sunday=6
weekday_name周中的星期几,ex: Friday
quarter季度
days_in_month一个月中有多少天
is_month_start是否月初第一天
is_month_end是否月末最后一天
is_quarter_start是否季度的最开始
is_quarter_end是否季度的最后一个
is_year_start是否年初第一天
is_year_end是否年末第一天

2、某一时间点,往前往后加一段时间

类别解释
BDay工作日
CDay自定义日期
Week
WeekOfMonth月中的第几周
LastWeekOfMonth月中的最后一周
MonthEnd日历上月末
MonthBegin日历上月初
BMonthEnd工作月初
BMonthBegin月开始营业
CBMonthEnd自定义月末
CBMonthBegin自定义月初
QuarterEnd日历季末
QuarterBegin日历季初
BQuarterEnd工作季末
BQuarterBegin工作季初
FY5253Quarterretail (aka 52-53 week) quarter
YearEnd日历年末
YearBegin日历年初
BYearEnd工作年末
BYearBegin工作年初
FY5253retail (aka 52-53 week) year
BusinessHour工作小时
CustomBusinessHour自定义小时
Hour小时
Minute分钟
Second
3.当数据很多,且日期格式不标准时的时候,如果pandas.to_datetime 函数使用不当,会使得处理时间变得很长,提升速度的关键在于format的使用。下面举例进行说明:

示例数据:

date 格式:02.01.2013 即 日.月.年 
数据量:3000000

df.head()
---------------------------------------------
          date  date_block_num  shop_id  item_id  item_price  item_cnt_day
0  02.01.2013               0       59    22154      999.00           1.0
1  03.01.2013               0       25     2552      899.00           1.0
2  05.01.2013               0       25     2552      899.00          -1.0
3  06.01.2013               0       25     2554     1709.05           1.0
4  15.01.2013               0       25     2555     1099.00           1.0

处理方式一:

df['date_formatted']=pd.to_datetime(df['date'],format='%d.%m.%Y')#这里的format='%d.%m.%Y'是指原始数据中的格式df['date'].dt.year#注意要加dt来获取年,月,日等等信息...

附录:format相关

代码说明
%Y4位数的年
%y2位数的年
%m2位数的月[01,12]
%d2位数的日[01,31]
%H时(24小时制)[00,23]
%l时(12小时制)[01,12]
%M2位数的分[00,59]
%S秒[00,61]有闰秒的存在
%w用整数表示的星期几[0(星期天),6]
%F%Y-%m-%d简写形式例如,2017-06-27
%D%m/%d/%y简写形式

4.周数的计算
 工作日的计算

Excel中有个很方便的函数叫networkdays,给出起始日期,结束日期和holiday可以计算两个日期间的工作天数。而pandas或者datetime对这个需求支持的不好,所以找到了这个module: business_calendar
https://pypi.python.org/pypi/business_calendar/

pip install workdays

NETWORKDAYS(start_date,end_date,holidays)
返回开始日期和结束日期之间的整个工作日数(包括 开始日期和结束日期)。工作日不包括周末和假日中确定的任何日期。
WORKDAY(start_date,days,[holidays])
Returns a number that represents a date that is the indicated number of working days before or after a date (the starting date). Working days exclude weekends and any dates identified as holidays. Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected delivery times, or the number of days of work performed.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值