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 | 工作季初 |
FY5253Quarter | retail (aka 52-53 week) quarter |
YearEnd | 日历年末 |
YearBegin | 日历年初 |
BYearEnd | 工作年末 |
BYearBegin | 工作年初 |
FY5253 | retail (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相关
代码 | 说明 |
---|---|
%Y | 4位数的年 |
%y | 2位数的年 |
%m | 2位数的月[01,12] |
%d | 2位数的日[01,31] |
%H | 时(24小时制)[00,23] |
%l | 时(12小时制)[01,12] |
%M | 2位数的分[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/
https://pypi.python.org/pypi/business_calendar/
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.