时间操作datetime,Timestamp,to_datetime,strptime用法

一, datetime.datetime()

import datetime
dt = datetime.datetime(year=2019,month=11,day=4,hour=10,minute=30)
dt

datetime.datetime(2019, 11, 4, 10, 30)

print(dt)

2019-11-04 10:30:00

二, pd.Timestamp()

import pandas as pd
ts = pd.Timestamp('2019-11-4')
print(ts)
print(ts.month)
print(ts.day)

2019-11-04 00:00:00
11
4

ts + pd.Timedelta('5 days')

Timestamp(‘2019-11-09 00:00:00’)

三, pd.to_datetime()

pd.to_datetime('2019-11-4')
# pd.to_datetime('11/4/2019')

Timestamp(‘2019-11-04 00:00:00’)

s = pd.Series(['2019-11-4 00:00:00','2019-11-5 00:00:00','2019-11-6 00:00:00'])
s
Out:
0    2019-11-4 00:00:00
1    2019-11-5 00:00:00
2    2019-11-6 00:00:00
dtype: object
ts = pd.to_datetime(s)
ts
# ts.dt.hour
# ts.dt.weekday
Out:
0   2019-11-04
1   2019-11-05
2   2019-11-06
dtype: datetime64[ns]

四, pandas数据中to_datetime的运用

data = pd.read_csv('flowdata.csv')
data.head()
Out:
             Time	    L06_347	    LS06_347	LS06_348
0	2009-01-01 00:00:00	0.137417	0.097500	0.016833
1	2009-01-01 03:00:00	0.131250	0.088833	0.016417
2	2009-01-01 06:00:00	0.113500	0.091250	0.016750
3	2009-01-01 09:00:00	0.135750	0.091500	0.016250
4	2009-01-01 12:00:00	0.140917	0.096167	0.017000
data['Time'] = pd.to_datetime(data['Time'])
data = data.set_index('Time') # 以时间为索引
data.head()
Out:
					L06_347		LS06_347	LS06_348
		Time			
2009-01-01 00:00:00	0.137417	0.097500	0.016833
2009-01-01 03:00:00	0.131250	0.088833	0.016417
2009-01-01 06:00:00	0.113500	0.091250	0.016750
2009-01-01 09:00:00	0.135750	0.091500	0.016250
  • 或者读取数据时,直接指定时间为数据的索引
data = pd.read_csv('flowdata.csv', index_col=0, parse_dates=True)
data.head() #结果跟上面一样
data[pd.Timestamp('2012-01-01 09:00'):pd.Timestamp('2012-01-01 19:00')]
# data[('2012-01-01 09:00'):('2012-01-01 19:00')] #简略写法
Out:
					L06_347		LS06_347	LS06_348
			Time			
2012-01-01 09:00:00	0.330750	0.293583	0.029750
2012-01-01 12:00:00	0.295000	0.285167	0.031750
2012-01-01 15:00:00	0.301417	0.287750	0.031417
2012-01-01 18:00:00	0.322083	0.304167	0.038083

五, datetime.strptime()

  • 语法: datetime.strptime(str, ‘%Y-%m-%d’)
import pandas as pd
data = pd.read_csv('temps.csv')
data.head()
Out:
	year month day week temp_2	temp_1	average	actual	friend
0	2016	1	1	Fri		45	45		45.6	45		29
1	2016	1	2	Sat		44	45		45.7	44		61
2	2016	1	3	Sun		45	44		45.8	41		56
3	2016	1	4	Mon		44	41		45.9	40		53
4	2016	1	5	Tues 	41	40		46.0	44		41
import datetime
years = data['year']
months = data['month']
days = data['day']

dates = [str(int(year))+'-'+str(int(month))+'-'+str(int(day)) for year,month,day in zip(years,months,days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
dates[:5]

[datetime.datetime(2016, 1, 1, 0, 0),
datetime.datetime(2016, 1, 2, 0, 0),
datetime.datetime(2016, 1, 3, 0, 0),
datetime.datetime(2016, 1, 4, 0, 0),
datetime.datetime(2016, 1, 5, 0, 0)]

  • 更多时间相关操作见: https://blog.csdn.net/sanjianjixiang/article/details/103018564

你可能感兴趣的:(python)