Search code examples
pythonpandas

Formatting month to the single digit with pandas


I have below code

import pandas as pd
pd.to_datetime(['8/23/1999']).strftime("%m/%d/%Y").astype('str')

This generates 08/23/1999

However I want to get 8/23/1999

Is there any specific formatting to be used for this case?


Solution

  • Updated following the comment from ouroboros1

    The solution below works only on Linux

    On Linux Pandas supports Glibc extensions (see man 3 strftime), so you can use the - flag.

    Glibc provides some extensions for conversion specifications. (These extensions are not specified in POSIX.1-2001, but a few other systems provide similar features.)
    Between the '%' character and the conversion specifier character, an optional flag and field width may be specified.

    ...

    The following flag characters are permitted:

    • _ (underscore) Pad a numeric result string with spaces.
    • - (dash) Do not pad a numeric result string.
    • 0 Pad a numeric result string with zeros even if the conversion specifier character uses space-padding by default.
    • ^ Convert alphabetic characters in result string to uppercase.
    • # Swap the case of the result string. (This flag works only with certain conversion specifier characters, and of these, it is only really useful with %Z.)

    For example:

    pd.to_datetime(['8/23/1999']).strftime("%-m/%d/%Y")
    

    This would produce an Index object with a string formatted without the padding.

    Index(['8/23/1999'], dtype='object')