在Pandas中从时间戳中获取小时数
让我们在多个例子的帮助下,看看如何在Pandas中从时间戳中提取小时。
示例1:
pandas.timestamp.now() 将时区作为输入,并返回该时区的当前时间戳对象。
# importing the module
import pandas as pd
# input current timestamp
date = pd.Timestamp.now()
print("currentTimestamp: ", date)
# extract the Hours from the timestamp
frame = date.hour
print("Hour: ", frame)
输出:
例子2:
pandas.timestamp()用于获取特定时区的DateTimeIndex。它将年、月、日、时间和时区作为输入,并返回该时区的DateTimeIndex。
# importing the module
import pandas as pd
# input the timestamp
date = pd.Timestamp(year = 2020, month = 7, day = 21,
hour = 6, minute = 30, second = 44,
tz = 'Asia / Kolkata')
print("Timestamp: ", date)
# extract the Hours from the timestamp
print("Hour: ", date.hour)
输出 :
示例3:
使用pandas.dt_range()将输入的时间戳作为范围,并使用pandas.series()转换为一个时间戳数组。
# importing the module
import pandas as pd
# take input Dates in a range
dates = pd.Series(pd.date_range('2019-8-5 10:23:05', periods = 6, freq ='H'))
# convert in a dict container
frame = pd.DataFrame(dict(givenDate = dates))
# extract Hours from Timestamp
frame['hourOfTimestamp'] = frame['givenDate'].dt.hour
print(frame)
输出 :
示例4 :
使用object.hour属性来返回给定系列对象的数据中的日期时间的小时。
# importing the module
import pandas as pd
# take inputs
dates = pd.Series(['2015-01-11 09:20', '2019-4-8 11:31', '2018-12-22 10:10',
'2011-4-2 04:25', '2017-1-6 03:51'])
# give a Name to the series
seriesName = ['T1', 'T2', 'T3', 'T4', 'T5']
# give index to each timestamp
dates.index = seriesName
dates = pd.to_datetime(dates)
# extract Hours from Timestamp
rs = dates.dt.hour
print(rs)
输出 :
示例5 :
从csv文件中读取时间戳数据,并从每个时间戳中获取小时。
# importing the module
import pandas as pd
# read the date from xyz.csv file
frame = pd.read_csv(r'xyz.csv')
print("Values in xyz.csv: ")
print(frame.head())
frame['dateTime'] = frame['dateTime'].astype('datetime64[ns]')
# extract Hours from Timestamp
print("Hours: ")
print(frame.dateTime.dt.hour.head())
输出 :