简体   繁体   English

在一种格式的熊猫中转换两种日期格式

[英]Converting two date formats in one format pandas

What would be the easiest way to transform two date formats in pandas dataframe into one? 将熊猫数据框中的两种日期格式转换为一种最简单的方法是什么? Below is my input 以下是我的输入

import pandas as pd
df = pd.DataFrame({'DOB': {0: '26/1/16 ', 1: '26/1/2016 '}})

Expected output: 预期产量:

       DOB
0   26/1/2016
1   26/1/2016

I need to maintain the same dateformat. 我需要保持相同的dateformat。

Followed the comments and used pd.to_datetime 关注了评论并使用了pd.to_datetime

pd.to_datetime(df.DOB)

Output: 输出:

0   2016-01-26
1   2016-01-26

Which is fine but I want to retain the original format of %d/%m/%Y 很好,但是我想保留%d/%m/%Y的原始格式

I have tried using the format argument after executing pd.to_datetime 我在执行pd.to_datetime之后尝试使用format参数

df.DOB=pd.to_datetime(df.DOB,format="%d/%m/%Y")

It seems it does not changes the format. 似乎它不会更改格式。 Output: 输出:

0   2016-01-26
1   2016-01-26

If I directly execute below to provide the format it gives error which makes sense as input is not of same format 如果我直接在下面执行以提供格式,则会产生错误,这是有道理的,因为输入格式不同

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '}})
df.DOB=pd.to_datetime(df.DOB,format="%d/%m/%Y")

ERROR: 错误:

ValueError: unconverted data remains:  

Long story short how can I retain the original date format 长话短说如何保留原始日期格式

You have whitespace in your date strings. 您的日期字符串中有空格。 Use pd.Series.str.strip before calling pd.to_datetime to guarantee you will avoid errors. 使用pd.Series.str.strip之前调用pd.to_datetime保证你会避免错误。

Option 1: don't specify format 选项1:不指定格式

Here you don't even need to strip whitespace: 在这里,您甚至不需要剥离空格:

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

df.DOB = pd.to_datetime(df.DOB)

print(df)

         DOB
0 2016-01-26
1 2016-01-26

Option 2: strip before specifying format 选项2:在指定格式之前删除

Supply format only if you know beforehand the specific format of your dates. 仅在事先知道日期的特定format时才提供format If you do this, you will need to use pd.Series.str.strip beforehand: 如果这样做,则需要预先使用pd.Series.str.strip

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

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

print(df)

         DOB
0 2016-01-26
1 2016-01-26

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM