Define date format in Python / Pandas
<p>I have two .csv files joined in Python with the Pandas module. One column is date with the format "dd.mm.yyyy".</p>

<p>Now I would like to extract only the month (as 2 digit integer with leading zero) from it for further use.</p>

<p>I have so far accomplished the job but I had to cheat. Python thinks the string that I am getting is the DAY. I don't like half-baked things, so I wanted to ask the community how I can tell Python specifically which part of the date is the month so it can be returned to me?</p>

<p>Here is what I have so far:</p>

<pre><code>import pandas

def saison(input):
    if input == "04" or input == "05" or input == "06" or input == "07" or input == "08" or input == "09":
        return "Sommer"
    else:
        return "Winter"

df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "Datum"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=[VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["Datum"] = pandas.to_datetime(df_joined["Datum"])

df_joined["Saison"] = saison(df_joined["Datum"].apply(lambda x: x.strftime('%d')))
</code></pre>

<p>If I use </p>

<pre><code>x.strftime('%m') 
</code></pre>

<p>instead it returns me the day.</p>

<p>You could supply the format you want to keep in the arg of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>

<pre><code>pd.to_datetime(df['date_col'], format="%d.%m.%Y").dt.month.astype(str).str.zfill(2)
</code></pre>

python python-2.7 csv pandas