如何更改 Pandas 中的日期时间格式 [英] How to change the datetime format in Pandas
问题描述
我的数据框有一个 DOB
列(示例格式 1/1/2016
),默认情况下它会转换为 Pandas dtype 'object':DOB object代码>
My dataframe has a DOB
column (example format 1/1/2016
) which by default gets converted to Pandas dtype 'object': DOB object
使用 df['DOB'] = pd.to_datetime(df['DOB'])
将此转换为日期格式,日期将转换为:2016-01-26
和它的 dtype
是:DOB datetime64[ns]
.
Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB'])
, the date gets converted to: 2016-01-26
and its 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列的代码> 将是
object
(string
)):
You can use dt.strftime
if you need to convert datetime
to other formats (but note that then dtype
of column will be 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屋!