在Pandas Dataframe中,将一系列的日期字符串转换为时间序列
在分析一个数据集的过程中,经常发生这样的情况,即日期没有以适当的类型表示,而是以简单的字符串呈现,这使得处理它们和对它们进行标准的日期-时间操作变得困难。
pandas.to_datetime() 函数有助于将一个日期字符串转换为一个Python日期对象。因此,它可以被用来将一系列的日期字符串转换为时间序列。
让我们看看一些例子。
示例 1:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['28 July 2020', '16 January 2013',
'29 February 2016 18:14'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after being
# converted to a time series
print("\nSeries of date strings after" +
" being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出:
示例 2:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['2020/07/28', '2013/01/16',
'2016/02/29 18:14'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after being
# converted to a time series
print("\nSeries of date strings after " +
"being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出:
示例 3:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['2020-07-28', '2013-01-16',
'2016-02-29 18:14'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after
# being converted to a time series
print("\nSeries of date strings after " +
"being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出:
示例 4:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['28/07/2020', '01/16/2013',
'29/02/2016 18:14'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after being
# converted to a time series
print("\nSeries of date strings after " +
"being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出:
示例 5:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['20200728', '20130116',
'20160229 181431'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after
# being converted to a time series
print("\nSeries of date strings after " +
"being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出:
示例 6:
# import pandas library
import pandas as pd
# create a series of date strings
dt_series = pd.Series(['28 July 2020', '2013-01-16',
'20160229 18:14', '5/03/2019 2215',
'20151204 09:23'])
# display the series initially
print("Series of date strings:")
print(dt_series)
# display the series after
# being converted to a time series
print("\nSeries of date strings after " +
"being converted to a timeseries:")
print(pd.to_datetime(dt_series))
输出: