36. Pandas的时间序列数据-Period时期

Pandas的Period可以定义一个时期,或者说具体的一个时段。有这个时段的起始时间start_time、终止时间end_time等属性信息,其参数freq和之前的date_range里的freq参数类似,可以取'S'、'D'等。

import pandas as pd
p = pd.Period('2018-12-15', freq = "A")
print p.start_time, p.end_time, p + 1, p
print pd.Period('2013-1-9 11:22:33', freq='S') + 1
print pd.Period('2013-1-9 11:22:33', freq='T') + 1
print pd.Period('2013-1-9 11:22:33', freq='H') + 1
print pd.Period('2013-1-9 11:22:33', freq='D') + 1
print pd.Period('2013-1-9 11:22:33', freq='M') + 1
print pd.Period('2013-1-9 11:22:33', freq='A') + 1

程序的执行结果如下:

2018-12-01 00:00:00 2018-12-31 23:59:59.999999999 2019-01
2018-01-01 00:00:00 2018-12-31 23:59:59.999999999 2019 2018
2013-01-09 11:22:34 # S 秒
2013-01-09 11:23 # T 分
2013-01-09 12:00 # H 时
2013-01-10 # D 天
2013-02 # M 月
2014 # A 年

Period数据类型的属性有:

day Get day of the month that a Period falls on.
dayofweek Return the day of the week.
dayofyear Return the day of the year.
days_in_month Get the total number of days in the month that this period falls on.
daysinmonth Get the total number of days of the month that the Period falls in.
hour Get the hour of the day component of the Period.
minute Get minute of the hour component of the Period.
second Get the second component of the Period.
start_time Get the Timestamp for the start of the period.
week Get the week of the year on the given Period.

下面可以编写程序使用一下这些属性。

import pandas as pd
att = ["S", "T", "H", "D", "M", "A"]
for a in att:
    p = pd.Period('2018-12-19 11:22:33', freq= a)
    print "freq =", a
    print "Start from:", p.start_time, " End at:", p.end_time
    print "Day",p.day, "Dayofweek", p.dayofweek,"dayofyear", p.dayofyear,"daysinmonth", p.daysinmonth
    print "hour", p.hour, "minute", p.minute, "second", p.second, "\n"

程序的执行结果:

freq = S
Start from: 2018-12-19 11:22:33  End at: 2018-12-19 11:22:33.999999999
Day 19 Dayofweek 2 dayofyear 353 daysinmonth 31
hour 11 minute 22 second 33 

freq = T
Start from: 2018-12-19 11:22:00  End at: 2018-12-19 11:22:59.999999999
Day 19 Dayofweek 2 dayofyear 353 daysinmonth 31
hour 11 minute 22 second 0 

freq = H
Start from: 2018-12-19 11:00:00  End at: 2018-12-19 11:59:59.999999999
Day 19 Dayofweek 2 dayofyear 353 daysinmonth 31
hour 11 minute 0 second 0 

freq = D
Start from: 2018-12-19 00:00:00  End at: 2018-12-19 23:59:59.999999999
Day 19 Dayofweek 2 dayofyear 353 daysinmonth 31
hour 0 minute 0 second 0 

freq = M
Start from: 2018-12-01 00:00:00  End at: 2018-12-31 23:59:59.999999999
Day 31 Dayofweek 0 dayofyear 365 daysinmonth 31
hour 0 minute 0 second 0 

freq = A
Start from: 2018-01-01 00:00:00  End at: 2018-12-31 23:59:59.999999999
Day 31 Dayofweek 0 dayofyear 365 daysinmonth 31
hour 0 minute 0 second 0