OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Convert date column with DDMMMYYYY strings into YYYYMMDD string in Pandas [duplicate]

  • Thread starter Thread starter CypherX
  • Start date Start date
C

CypherX

Guest
Convert a date column loaded as strings into a pandas dataframe, in the format DDMMMYYYY (i.e. %d%b%Y) to the desired format of YYYYMMDD (i.e. %Y%m%d).

Example: Convert 31Oct2023 to 20231031.

Code:
   GivenInput ExpectedDates
0   31Jan2023      20230131
1   28Feb2023      20230228
2   31Mar2023      20230331
3   30Apr2023      20230430
4   31May2023      20230531
5   30Jun2023      20230630
6   31Jul2023      20230731
7   31Aug2023      20230831
8   30Sep2023      20230930
9   31Oct2023      20231031
10  30Nov2023      20231130
11  31Dec2023      20231231
12  31Jan2024      20240131
13  29Feb2024      20240229
14  31Mar2024      20240331
15  30Apr2024      20240430
16  31May2024      20240531

Snippet to load the sample data:

Code:
import pandas as pd
from io import StringIO

s = """
GivenInput
31Jan2023
28Feb2023
31Mar2023
30Apr2023
31May2023
30Jun2023
31Jul2023
31Aug2023
30Sep2023
31Oct2023
30Nov2023
31Dec2023
31Jan2024
29Feb2024
31Mar2024
30Apr2024
31May2024
"""
s = s.strip()

df = pd.read_csv(StringIO(s))
print(df)
<p>Convert a date column loaded as strings into a pandas dataframe, in the format <code>DDMMMYYYY</code> (i.e. <code>%d%b%Y</code>) to the desired format of <code>YYYYMMDD</code> (i.e. <code>%Y%m%d</code>).</p>
<p>Example: Convert <code>31Oct2023</code> to <code>20231031</code>.</p>
<pre class="lang-none prettyprint-override"><code> GivenInput ExpectedDates
0 31Jan2023 20230131
1 28Feb2023 20230228
2 31Mar2023 20230331
3 30Apr2023 20230430
4 31May2023 20230531
5 30Jun2023 20230630
6 31Jul2023 20230731
7 31Aug2023 20230831
8 30Sep2023 20230930
9 31Oct2023 20231031
10 30Nov2023 20231130
11 31Dec2023 20231231
12 31Jan2024 20240131
13 29Feb2024 20240229
14 31Mar2024 20240331
15 30Apr2024 20240430
16 31May2024 20240531
</code></pre>
<p>Snippet to load the sample data:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from io import StringIO

s = """
GivenInput
31Jan2023
28Feb2023
31Mar2023
30Apr2023
31May2023
30Jun2023
31Jul2023
31Aug2023
30Sep2023
31Oct2023
30Nov2023
31Dec2023
31Jan2024
29Feb2024
31Mar2024
30Apr2024
31May2024
"""
s = s.strip()

df = pd.read_csv(StringIO(s))
print(df)
</code></pre>
 

Latest posts

Top