如何在 Pandas 中将数据格式更改为“%Y%m%d”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51310072/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:48:02  来源:igfitidea点击:

How to change format of data to '%Y%m%d' in Pandas?

pythonstringpandasdateseries

提问by Joe

I have a DF with first column showing as e.g. 2018-01-31 00:00:00.

我有一个 DF,第一列显示为例如2018-01-31 00:00:00

I want to convert whole column (or during printing / saving to other variable) that date to 20180131format. NOT looking to do that during saving to a CSV file.

我想将该日期的整列(或在打印/保存到其他变量期间)20180131转换为格式。在保存到 CSV 文件期间不希望这样做。

Tried this but it did not work:

试过这个,但没有用:

df['mydate'] = pd.to_datetime(df['mydate'], format='%Y%m%d')

df['mydate'] = pd.to_datetime(df['mydate'], format='%Y%m%d')

回答by jpp

pd.to_datetimeis used to convert your series to datetime:

pd.to_datetime用于将您的系列转换为datetime

s = pd.Series(['2018-01-31 00:00:00'])
s = pd.to_datetime(s)

print(s)

0   2018-01-31
dtype: datetime64[ns]

pd.Series.dt.strftimeconverts your datetimeseries to a string in your desired format:

pd.Series.dt.strftime将您的datetime系列转换为所需格式的字符串:

s = s.dt.strftime('%Y%m%d')

print(s)

0    20180131
dtype: object

回答by Dan

pd.to_datetimewill convert a string to a date. You want to covert a date to a string

pd.to_datetime将字符串转换为日期。您想将日期转换为字符串

df['mydate'].dt.strftime('%Y%m%d')

Note that it's possible your date is already a string, but in the wrong format in which case you maight have to convert it to a date first:

请注意,您的日期可能已经是一个字符串,但格式错误,在这种情况下,您可能必须先将其转换为日期:

pd.to_datetime(df['mydate'], format='%Y-%m-%d %H:%M:S').dt.strftime('%Y%m%d')