如何更改 pandas 的日期时间格式

编程入门 行业动态 更新时间:2024-10-27 07:26:00
本文介绍了如何更改 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 的日期时间格式

本文发布于:2023-07-23 19:22:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何更改   日期   格式   时间   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!