以下答案中有一个广泛引用的方法,用于在使用pandas to_csv时指定日期格式:
How to specify date format when using pandas.to_csv?
这个答案描述:
date_format='%Y%m%d'
但我有一个不同的要求,哪个找不到任何信息。
如何为实际年/月/日令牌指定不同的日期格式?
... date_format ='%Y%m%d'...转换为截至今天的2014/10/2。我可以使用这些信息来处理相同的数据 - 例如10/2/2014,但我不能改变格式本身。
我想输出02-Oct_2014。我试过'%dd%mmm%yyyy'但是额外的字母只是作为额外的字母添加 - 日期格式没有变化。
是否可以指定除'%Y%m%d'的排列以外的格式?
答案 0 :(得分:3)
Pandas使用strftime
,因此请使用the format codes it specifies。
对于02-Oct_2014
,您似乎想要%d-%b_%Y
>>> df = pd.DataFrame(list(range(5)), index=pd.date_range('10/1/14', periods=5))
>>> print(df.to_csv(date_format='%d-%b_%Y'))
,0
01-Oct_2014,0
02-Oct_2014,1
03-Oct_2014,2
04-Oct_2014,3
05-Oct_2014,4
答案 1 :(得分:1)
您想要的格式为'%d-%b_%Y'
。我怎么知道这个?我查看了man strftime,因为这是在引擎盖下使用的(或模拟它)。我搜索了文档“月”,发现了这个:
%b is replaced by national representation of the abbreviated month name.
这里也显示了Python文档:https://docs.python.org/2/library/time.html#time.strftime
最后,您可以直接在* nix命令行上测试许多此类格式,如下所示:
date +%d-%b_%Y