pandas 如何使用熊猫更改数据框中的日期时间格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47560533/
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
How to change datetime format in dataframe with using pandas?
提问by Haven Shi
I'm a pandas learner.
我是Pandas学习者。
I have a dataframe with the column 'DATE', the datetime format of the column is like '11/1/2017 1:00'. I want to change the datetime format from '11/1/2017 1:00' to '1-Dec-17 1:00', I tried the following code:
我有一个包含“DATE”列的数据框,该列的日期时间格式类似于“11/1/2017 1:00”。我想将日期时间格式从“11/1/2017 1:00”更改为“1-Dec-17 1:00”,我尝试了以下代码:
dir_path = os.path.dirname(os.path.realpath("__file__"))
print(dir_path)
def parse_dates(x):
return datetime.strptime(x, "%d-%b-%y %H:%M")
df = pd.read_csv(dir_path+"/TEST.csv", parse_dates=['DATE'],date_parser=parse_dates)
But it shows error:
但它显示错误:
ValueError: time data '11/1/2017 1:00' does not match format '%d-%b-%y %H:%M'
ValueError: 时间数据 '11/1/2017 1:00' 与格式 '%d-%b-%y %H:%M' 不匹配
I also tried to convert the dataframe, but failed:
我也尝试转换数据帧,但失败了:
df=pd.read_csv(dir_path+"/TEST.csv")
df['DATE'] = pd.to_datetime(df['DATE'],format='%d-%b-%y %H:%M')
Again, it shows error:
再次,它显示错误:
ValueError: time data '11/1/2017 1:00' does not match format '%d-%b-%y %H:%M' (match)
ValueError: 时间数据 '11/1/2017 1:00' 不匹配格式 '%d-%b-%y %H:%M'(匹配)
How to solve the problem? Thank you for your time!
如何解决问题?感谢您的时间!
采纳答案by YOBEN_S
df=pd.DataFrame({'Time':[ '11/1/2017 1:00', '11/1/2017 1:00', '11/1/2017 1:00', '11/1/2017 1:00']})
df.Time=pd.to_datetime(df.Time).dt.strftime('%d-%b-%y %H:%M')
df
Out[870]:
Time
0 01-Nov-17 01:00
1 01-Nov-17 01:00
2 01-Nov-17 01:00
3 01-Nov-17 01:00
回答by Atto Allas
The simple answer is that your format
argument to the strptime function is wrong. You want datetime.strptime(x, "%m-%d-%Y %H:%M")
.
简单的答案是您format
对 strptime 函数的论证是错误的。你要datetime.strptime(x, "%m-%d-%Y %H:%M")
。
Also, make sure that all of your numbers are padded (i.e. for the month, make sure it is 01 for Jan instead of 1. Same idea for minutes and days), otherwise this may fail.
此外,请确保您的所有数字都已填充(即对于月份,请确保 Jan 是 01 而不是 1。分钟和天数的想法相同),否则这可能会失败。
I would recommend you take a look at the python page for strptime formattingin order to learn more about how to format dates.
我建议您查看strptime 格式的python 页面,以了解有关如何设置日期格式的更多信息。