一、以下有两种方式可以创建一个Timestamp对象:
1. Timestamp()的构造方法
import pandas as pd
from datetime import datetime as dt
p1=pd.Timestamp(2017,6,19)
p2=pd.Timestamp(dt(2017,6,19,hour=9,minute=13,second=45))
p3=pd.Timestamp("2017-6-19 9:13:45")
print("type of p1:",type(p1))
print(p1)
print("type of p2:",type(p2))
print(p2)
print("type of p3:",type(p3))
print(p3)
输出:
('type of p1:', <class 'pandas.tslib.Timestamp'>)
2017-06-19 00:00:00
('type of p2:', <class 'pandas.tslib.Timestamp'>)
2017-06-19 09:13:45
('type of p3:', <class 'pandas.tslib.Timestamp'>)
2017-06-19 09:13:45
2. to_datetime()方法
import pandas as pd
from datetime import datetime as dt
p4=pd.to_datetime("2017-6-19 9:13:45")
p5=pd.to_datetime(dt(2017,6,19,hour=9,minute=13,second=45))
print("type of p4:",type(p4))
print(p4)
print("type of p5:",type(p5))
print(p5)
输出:
('type of p4:', <class 'pandas.tslib.Timestamp'>)
2017-06-19 09:13:45
('type of p5:', <class 'pandas.tslib.Timestamp'>)
2017-06-19 09:13:45
datetime模块的对象有如下:
- timedelta
- date
- datetime
- time
- tzinfo
还包含以下两个常量:
- datetime.MINYEAR (它返回的是1)
- datetime.MAXYEAR(它返回的是9999)
二、datetime对象
它的构造方法:
class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
year, month 和 day 参数是必须的,其他参数可选, 参数tzinfo表示可选的时区信息,一般我们也用不到。参数值的范围如下:
- MINYEAR <= year <= MAXYEAR
- 1 <= month <= 12
- 1 <= day <= number of days in the given month and year
- 0 <= hour < 24
- 0 <= minute < 60
- 0 <= second < 60
- 0 <= microsecond < 1000000
我们平常能用到的也就是年,月,日,时,分,秒,其他参数可以不用管。下面通过例子认识下datetime对象。
from datetime import datetime as dt
t=dt(2017,6,1,hour=13,minute=17,second=30)
print(type(t))
print(t)
输出:
<type 'datetime.datetime'>
2017-06-01 13:17:30
如果我们只传参数year, month, day,那么时间会默认变成00:00:00,看下面的代码:
from datetime import datetime as dt
t=dt(2017,6,1)
print(t)
输出:2017-06-01 00:00:00
下面我们看下datetime对象的几个方法:
datetime.today() 返回本地当前的时间
from datetime import datetime as dt
print(dt.today())
输出:2017-06-18 13:21:16.201000
datetime.now([tz]) 返回本地当前的日期和时间。如果可选的参数 tz 为 None 或者没有指定,就如同today()
from datetime import datetime as dt
print(dt.now())
输出:2017-06-18 13:23:33.536000
datetime对象还有两个属性:min和max
from datetime import datetime as dt
min_time=dt.min
max_time=dt.max
print(min_time)
print(max_time)
输出:
0001-01-01 00:00:00
9999-12-31 23:59:59.999999