日期时间与python Pandas中的系列字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30132282/
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
datetime to string with series in python pandas
提问by Diego
I need to make this simple thing:
我需要做这个简单的事情:
dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str
But a get an error. How should I transform from datetime to string
但是一个得到一个错误。我应该如何从日期时间转换为字符串
Thanks in advance
提前致谢
采纳答案by EdChum
There is no str
accessor for datetimes and you can't do dates.astype(str)
either, you can call apply
and use datetime.strftime
:
str
日期时间没有访问器,您也不能这样做dates.astype(str)
,您可以调用apply
并使用datetime.strftime
:
In [73]:
dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0 2001-01-01
1 2001-03-31
dtype: object
You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.
您可以使用任何您喜欢的方式更改日期字符串的格式:strftime() 和 strptime() Behavior。
Update
更新
As of version 0.17.0
you can do this using dt.strftime
从版本开始,0.17.0
您可以使用dt.strftime
dates.dt.strftime('%Y-%m-%d')
will now work
现在可以工作
回答by Kamil Sindi
回答by Qing Xia
There is a pandas function that can be applied to DateTime index in pandas data frame.
有一个 pandas 函数可以应用于 pandas 数据框中的 DateTime 索引。
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
列表中的元素:
u'1910-11-02'
You might need to replace the 'u'.
您可能需要替换“u”。
There might be some additional arguments that I should put into the previous functions.
可能有一些额外的参数我应该放入之前的函数中。