在Python Pandas中从时间戳中获取秒数
在这个程序中,我们的任务是在Python中创建一个程序,从一个给定的时间戳中提取秒数。我们将使用DateTime对象的s属性来提取秒。
例子:如果我们有一个数据框,其中包含5个不同的时间戳,如:
Timestamp
2012-12-11 04:12:01
2013-10-13 04:12:04
2014-12-14 04:12:05
2015-11-15 04:12:06
2016-10-15 04:12:07
而我们的任务是从给定的时间戳中提取秒数。所以这里的输出将是。
seconds
1
4
5
6
7
例子1 :
# importing the module
import pandas as pd
# generating 10 timestamp starting from '2016-10-10 09:21:12'
date1 = pd.Series(pd.date_range('2016-10-10 09:21:12',
periods = 10, freq = 's'))
# converting pandas series into data frame
df = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1))
# extracting seconds from time stamp
df['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second
# displaying DataFrame
display(df)
输出 :
例子2 :
# importing the module
import pandas as pd
# generating 5 timestamp starting from '2020-01-01 00:00:00'
date1 = pd.Series(pd.date_range('2020-01-01 00:00:00',
periods = 5, freq = 's'))
# converting pandas series into data frame
df = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1))
# extracting seconds from time stamp
df['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second
# displaying DataFrame
display(df)
输出 :