Python 如何将 Pandas 数据框中的日期转换为“日期”数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16852911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert dates in a Pandas data frame to a 'date' data type?
提问by user7289
I have a Pandas data frame, one of the columns of which contains date strings in the format 'YYYY-MM-DD' e.g. '2013-10-28'.
我有一个 Pandas 数据框,其中一列包含格式为“YYYY-MM-DD”的日期字符串,例如“2013-10-28”。
At the moment the dtype of the column is 'object'.
目前该列的 dtype 是“对象”。
How do I convert the column values to Pandas date format?
如何将列值转换为 Pandas 日期格式?
采纳答案by waitingkuo
回答by Andy Hayden
Essentially equivalent to @waitingkuo, but I would use to_datetimehere (it seems a little cleaner, and offers some additional functionality e.g. dayfirst):
本质上等同于@waitingkuo,但我会to_datetime在这里使用(它看起来更简洁,并提供了一些额外的功能,例如dayfirst):
In [11]: df
Out[11]:
a time
0 1 2013-01-01
1 2 2013-01-02
2 3 2013-01-03
In [12]: pd.to_datetime(df['time'])
Out[12]:
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
Name: time, dtype: datetime64[ns]
In [13]: df['time'] = pd.to_datetime(df['time'])
In [14]: df
Out[14]:
a time
0 1 2013-01-01 00:00:00
1 2 2013-01-02 00:00:00
2 3 2013-01-03 00:00:00
Handling ValueErrors
If you run into a situation where doing
处理ValueErrors
如果您遇到以下情况
df['time'] = pd.to_datetime(df['time'])
Throws a
抛出一个
ValueError: Unknown string format
That means you have invalid (non-coercible) values. If you are okay with having them converted to pd.NaT, you can add an errors='coerce'argument to to_datetime:
这意味着您有无效(不可强制)的值。如果您同意将它们转换为pd.NaT,则可以向 中添加一个errors='coerce'参数to_datetime:
df['time'] = pd.to_datetime(df['time'], errors='coerce')
回答by fantabolous
I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read:
我想很多数据从 CSV 文件进入 Pandas,在这种情况下,您可以在初始 CSV 读取期间简单地转换日期:
dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])where the 0 refers to the column the date is in.
You could also add , index_col=0in there if you want the date to be your index.
dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])其中 0 指的是日期所在的列。如果您希望日期成为索引,
您也可以, index_col=0在那里添加。
See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
见https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
回答by szeitlin
Now you can do df['column'].dt.date
现在你可以做 df['column'].dt.date
Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.
请注意,对于日期时间对象,如果您没有看到它们都是 00:00:00 的小时,那不是熊猫。那是 iPython 笔记本,试图让事情看起来很漂亮。
回答by Ted M.
It may be the case that dates need to be converted to a different frequency. In this case, I would suggest setting an index by dates.
可能需要将日期转换为不同的频率。在这种情况下,我建议按日期设置索引。
#set an index by dates
df.set_index(['time'], drop=True, inplace=True)
After this, you can more easily convert to the type of date format you will need most. Below, I sequentially convert to a number of date formats, ultimately ending up with a set of daily dates at the beginning of the month.
在此之后,您可以更轻松地转换为您最需要的日期格式类型。下面,我依次转换为多种日期格式,最终以月初的一组每日日期结束。
#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)
#Convert to monthly dates
df.index = df.index.to_period(freq='M')
#Convert to strings
df.index = df.index.strftime('%Y-%m')
#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)
For brevity, I don't show that I run the following code after each line above:
为简洁起见,我没有在上面的每一行之后显示我运行以下代码:
print(df.index)
print(df.index.dtype)
print(type(df.index))
This gives me the following output:
这给了我以下输出:
Index(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='object', name='time')
object
<class 'pandas.core.indexes.base.Index'>
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='datetime64[ns]', name='time', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
PeriodIndex(['2013-01', '2013-01', '2013-01'], dtype='period[M]', name='time', freq='M')
period[M]
<class 'pandas.core.indexes.period.PeriodIndex'>
Index(['2013-01', '2013-01', '2013-01'], dtype='object')
object
<class 'pandas.core.indexes.base.Index'>
DatetimeIndex(['2013-01-01', '2013-01-01', '2013-01-01'], dtype='datetime64[ns]', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
回答by SSS
Another way to do this and this works well if you have multiple columns to convert to datetime.
如果您有多个列要转换为日期时间,则另一种方法可以很好地执行此操作。
cols = ['date1','date2']
df[cols] = df[cols].apply(pd.to_datetime)
回答by David Valenzuela Urrutia
If you want to get the DATE and not DATETIME format:
如果要获取 DATE 而不是 DATETIME 格式:
df["id_date"] = pd.to_datetime(df["id_date"]).dt.date
回答by Mwanaidi Nicole
Try to convert one of the rows into timestamp using the pd.to_datetime function and then use .map to map the formular to the entire column
尝试使用 pd.to_datetime 函数将其中一行转换为时间戳,然后使用 .map 将公式映射到整列

