Python 如何更改熊猫中的日期时间格式

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

How to change the datetime format in pandas

pythonstringpandasdatetimestrftime

提问by yome

My dataframe has a DOBcolumn (example format 1/1/2016) which by default gets converted to pandas dtype 'object': DOB object

我的数据框有一个DOB列(示例格式1/1/2016),默认情况下它会转换为 pandas dtype 'object':DOB object

Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']), the date gets converted to: 2016-01-26and its dtypeis: DOB datetime64[ns].

使用 将其转换为日期格式df['DOB'] = pd.to_datetime(df['DOB']),日期将转换为:2016-01-26dtype为: DOB datetime64[ns]

Now I want to convert this date format to 01/26/2016or in any other general date formats. How do I do it?

现在我想将此日期格式转换为01/26/2016或转换为任何其他通用日期格式。我该怎么做?

Whatever the method I try, it always shows the date in 2016-01-26format.

无论我尝试什么方法,它总是以2016-01-26格式显示日期。

回答by jezrael

You can use dt.strftimeif you need to convert datetimeto other formats (but note that then dtypeof column will be object(string)):

dt.strftime如果需要转换datetime为其他格式,可以使用(但请注意,dtype列的then将为object( string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

回答by Yanni Cao

Changing the format but not changing the type:

更改格式但不更改类型:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

回答by rishi jain

The below code worked for me instead of the previous one - try it out !

下面的代码对我有用,而不是前一个 - 试试看!

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

回答by user3512680

Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.

与第一个答案相比,我会建议先使用 dt.strftime(),然后是 pd.to_datetime()。这样,它仍然会导致日期时间数据类型。

For example,

例如,

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)

df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)

回答by MarianD

The important note:

重要说明:

The following approach (styling) only works under Jupyter notebook, and will have no effect whatsoever when run outside Jupyter notebook.

以下方法(样式)仅在 Jupyter Notebook 下有效,在 Jupyter Notebook 之外运行时将不起作用。



There is a difference between the contentof a dataframe cell (a binary value) and its presentation(displaying it) for us, humans.

数据帧单元格的内容(二进制值)与其对我们人类的呈现(显示)之间存在差异。

If you use the Jupyter notebookfor displaying your dataframe, or if you want to present it in the form of an HTML file (with many idand classatributes for futher CSS styling, if you wish it), you may use styling.

如果您使用Jupyter笔记本电脑显示你的数据帧,或者如果你想目前它在一个HTML文件的形式(与许多idclassatributes获得进一步的CSS样式,如果你愿意的话),你可以使用样式

I will suppose that your column DOBalready has the type datetime64(you shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:

我会假设您的列DOB已经具有该类型datetime64(您表明您知道如何访问它)。我准备了一个简单的数据框(只有一列)来向您展示一些基本样式:

  • Not styled:

     df
    
              DOB
    0  2019-07-03
    1  2019-08-03
    2  2019-09-03
    3  2019-10-03
    
  • Styling it as mm/dd/yyyy:

     df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
    
              DOB
    0  07/03/2019
    1  08/03/2019
    2  09/03/2019
    3  10/03/2019
    
  • Styling it as dd-mm-yyyy:

     df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
    
              DOB
    0  03-07-2019
    1  03-08-2019
    2  03-09-2019
    3  03-10-2019
    
  • 没有样式:

     df
    
              DOB
    0  2019-07-03
    1  2019-08-03
    2  2019-09-03
    3  2019-10-03
    
  • 将其样式为mm/dd/yyyy

     df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
    
              DOB
    0  07/03/2019
    1  08/03/2019
    2  09/03/2019
    3  10/03/2019
    
  • 将其样式为dd-mm-yyyy

     df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
    
              DOB
    0  03-07-2019
    1  03-08-2019
    2  03-09-2019
    3  03-10-2019
    


Be careful! The returning object is NOT a dataframe — it is an object of the class Styler, so don't assign it back to df:

当心!返回的对象不是数据帧——它是类的对象Styler,所以不要将它分配回df

Notes/Pitfalls

注意事项/陷阱

a) Don't assign the styler object back to its parent dataframe:

a) 不要将样式器对象分配回其父数据框:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don′t do this!

(Every dataframe has its Styler object accessible by its .styleproperty, and we changed this df.styleobject, not the dataframe itself.)

(每个数据框都可以通过其.style属性访问它的 Styler 对象,我们更改了这个df.style对象,而不是数据框本身。)



b) Why your Styler object(or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?

b)为什么在 Jupyter 笔记本单元格中用作最后一个命令的 Styler 对象(或返回它的表达式)显示您的(样式化的) table,而不是 Styler 对象本身?

Because every Styler object has a callback method ._repr_html_()which returns an HTML code for rendering your dataframe (as a nice HTML table).

因为每个 Styler 对象都有一个回调方法._repr_html_(),该方法返回用于呈现数据帧的 HTML 代码(作为一个不错的 HTML 表格)。

Jupyter Notebook IDE calls this method automaticallyto render objects which have it.

Jupyter Notebook IDE 会自动调用此方法来渲染具有它的对象。



c) A Styler object has a render()method too, if you want to obtain a string with the HTML code (e.g. for publishing your formatted dataframe to the Web):

c) Styler 对象也有一个render()方法,如果您想获取带有 HTML 代码的字符串(例如,用于将格式化的数据帧发布到 Web):

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()

回答by San

Below code changes to 'datetime' type and also formats in the given format string. Works well!

下面的代码更改为 'datetime' 类型,并以给定的格式字符串进行格式化。效果很好!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

回答by Ashu007

You can try this it'll convert the date format to DD-MM-YYYY:

你可以试试这个,它会将日期格式转换为 DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)