[英]Pandas: can't convert datetime YYYY-mm-dd to dd-mm-YYYY
I have a pandas dataframe with column with dates (datetime64[ns] format) The dates are listed as yyyy-mm-dd (like 2018-09-12). 我有一个带有日期列(日期时间64 [ns]格式)的pandas数据框,日期以yyyy-mm-dd列出(如2018-09-12)。 I want to convert it to dd-mm-yyyy but what i try doesn't seem to works:
我想将其转换为dd-mm-yyyy,但我尝试执行的操作似乎无效:
pd.to_datetime(df['date'], format='%d-%m-%Y')
0 2018-09-12
1 2018-09-12
Edit: add example df 编辑:添加示例df
df.head(3)
date nr
0 2018-09-12 144
1 2018-09-12 37
2 2018-09-12 28
df.info()
date datetime64[ns]
nr int
The 'date' doesn't contain any Nan's or Nat's “日期”不包含任何Nan或Nat
You need to convert the date parsed with to_datetime
to a string in the desired representation. 您需要将使用
to_datetime
解析的日期转换为所需表示形式的字符串。 The display format you see right now is the default one used for Datetime
objects: 您现在看到的显示格式是用于
Datetime
对象的默认格式:
In [10]: frame = {'date': ['2018-09-12', '2016-10-02']}
In [11]: pd.to_datetime(frame['date']).strftime('%d-%m-%Y')
Out[11]: Index(['12-09-2018', '02-10-2016'], dtype='object')
The dates are listed as yyyy-mm-dd (like 2018-09-12).
日期以yyyy-mm-dd列出(例如2018-09-12)。
Yes, but this is not how they are stored. 是的,但这不是它们的存储方式。 What you are seeing is a specific string representation of
datetime
objects. 您将看到
datetime
对象的特定字符串表示形式 。 Internally, datetime
values are stored as integers . 在内部,
datetime
值存储为integers 。
I want to convert it to dd-mm-yyyy but what i try doesn't seem to works
我想将其转换为dd-mm-yyyy,但我尝试执行的操作似乎无效
Correct, because pd.to_datetime
converts to a datetime
object. 正确,因为
pd.to_datetime
转换为datetime
对象。 You need to instead convert your series to a series of strings, which will have object
dtype: 您需要将系列转换为一系列字符串,这些字符串将具有
object
dtype:
df['date'] = df['date'].dt.strftime('%d-%m-%Y')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.