2

There is a widely-quoted method in the following answer for specifying date format when using pandas to_csv:

How to specify date format when using pandas.to_csv?

This answer describes:

 date_format='%Y%m%d' 

But I have a different requirement for which can find no information.

How can I specify a different date format for the actual year/month/day tokens?

...date_format='%Y%m%d'... translates to 2014/10/2 as of today's date. I can use this information to juggle the same data around -- eg 10/2/2014, but I cannot change the format itself.

I would like to output 02-Oct_2014. I tried '%dd%mmm%yyyy' but the extra letters are just added as extra letters -- no change in the date format.

Is it possible to specify formats other than permutations of '%Y%m%d'?

Community
  • 1
  • 1
rdh9
  • 665
  • 2
  • 11
  • 20
  • Your date format string looks wrong, with three m's. Month abbreviations are %b. – ako Oct 04 '14 at 05:58

2 Answers2

3

Pandas uses strftime, so use the format codes it specifies.

For 02-Oct_2014 it looks like you want %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
Nick T
  • 25,754
  • 12
  • 83
  • 121
1

The format you want is '%d-%b_%Y'. How did I figure this out? I looked at man strftime because that's what is being used under the hood (or an emulation of it). I searched the docs for "month" and found this:

 %b    is replaced by national representation of the abbreviated month name.

It's also shown in the Python docs here: https://docs.python.org/2/library/time.html#time.strftime

And finally, you can test many such formats directly on the *nix command line like so:

date +%d-%b_%Y
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thankyou very much for the help, it works fine. As you both posted pretty much the same answer and explanation, I accepted the first one to arrive. I hope that's fair. – rdh9 Oct 04 '14 at 15:08