如何更改 pandas 的日期时间格式 [英] How to change the datetime format in pandas
本文介绍了如何更改 pandas 的日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
DOB列示例值的格式为 - 1/1/2016
其默认情况下转换为对象,如下所示
DOB column sample value is in the format - 1/1/2016
which by default gets converted to object as shown below
DOB object
转换为日期格式
df['DOB'] = pd.to_datetime(df['DOB'])
日期转换为
2016-01-26
dtype
is
DOB datetime64[ns]
现在我想将这个日期格式转换成 01/26/2016
或任何其他一般的日期格式。我如何做?
Now I want to convert this date format to 01/26/2016
or in any other general date formats. How do I do it?
无论我尝试什么方法总是显示日期在 2016-01-26
Whatever the method I try it always shows the date in 2016-01-26
format.
推荐答案
您可以使用 dt.strftime
,如果需要转换 datetime
到其他格式,但是列的 dtype
对象( string
You can use dt.strftime
, if need convert datetime
to other formats, but then dtype
of column is 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
这篇关于如何更改 pandas 的日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文